最普通的文件读写

普通文件的读写操作,样例如下:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>

int main(){

char buf[10];
int n, fd;
struct stat file_stat;

stat("test", &file_stat);
printf("文件设备编号:%d\n", (int)file_stat.st_dev);
printf("节点:%d\n", (int)file_stat.st_ino);
printf("文夹类型:%d\n", (int)file_stat.st_mode);
printf("硬链接数目:%d\n", (int)file_stat.st_nlink);
return 0;

/**
* 用读文件的方式从标准输入中读取,然后写回标准输出
*/
n = read(STDIN_FILENO, buf, 10);
if(n < 0){
perror("读取发生错误");
exit(1);
}
write(STDOUT_FILENO, buf, n);

/**
* 创建一个文件
*/
fd = open("test", O_CREAT, S_IRWXU);
close(fd);

/**
* 把字符存写入文件
*/
fd = open("test", O_WRONLY);
n = write(fd, buf, sizeof(buf));
close(fd);

/**
* 打开普通的文件读取字符
*/
fd = open("test", O_RDONLY);
n = read(fd, buf, sizeof(buf));
printf("%s\n", buf);
close(fd);

/**
* 重定位操作的位置
*/
fd = open("test", O_WRONLY);
n = lseek(fd, 10, SEEK_SET);
n = write(fd, buf, sizeof(buf));
close(fd);

/**
* 截短文件(也可用变长)
*/
fd = open("test", O_RDWR);
n = ftruncate(fd, 14);
close(fd);

return 0;
}



posted @ 2011-09-22 15:40  GG大婶  阅读(229)  评论(0编辑  收藏  举报