UNIX环境高级编程学习之第三章文件IO-文件读操作
[code lang="cpp"]
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int err_sys(const char * str)
{
printf("%s/n", str);
exit(-1);
return 0;
}
int main(int argc, char *argv[])
{
int fd;
fd = open("./a.txt", O_RDONLY);
if (-1 == fd)
{
err_sys(strerror(errno));
}
int i;
double d;
float f;
char c;
char str[100] = { '/0' };
int ret = read(fd, &i, sizeof(i));
if (ret != 4)
{
err_sys("read error!");
}
ret = read(fd, &d, sizeof(double));
if (ret != sizeof(double))
{
err_sys("read error! ");
}
ret = read(fd, &f, sizeof(f));
if (ret != sizeof(f))
{
err_sys("read error!");
}
ret = read(fd, &c, sizeof(c));
if (ret != sizeof(c))
{
err_sys("read error!");
}
ret = read(fd, str, sizeof(str));
if (ret != sizeof(str))
{
err_sys("read error!");
}
close(fd);
printf("i=%d, d=%lf, f=%f, c=%c, str=%s/n", i, d, f, c, str);
}
[/code]
文章评论