本用例简单联系Linux 下文件操作测试,基本过程是:
运行程序打开指定文件;
将buf_write数据写进文件;
将文件数据读取到buf_read;
最后打印出读取到文件。
//read.c
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
#include <sys/types.h>
#include <unistd.h>
#define BUF_SIZE 1024
int main(int argc,char*argv[])
{
int fd;
char buf_read[BUF_SIZE];
char buf_write[]="hello world!";
if(argc!=2)
{
printf("please input %s file name\n",argv[0]);
return 0;
}
unlink(argv[1]);
fd=open(argv[1],O_RDWR|O_CREAT|O_EXCL,S_IRWXU);//打开文件
if(-1==fd)//打开失败则返回-1
{
perror("open");
return -1;
}
int num_write=write(fd,buf_write,strlen(buf_write));//将buf_write 内容写进fd指向文件
printf("num_write=%d\n",num_write);
if(-1==num_write)
{
perror("write");
return -1;
}
lseek(fd,0,SEEK_SET);//z在写操作后fd 文件描述符指向文件末尾,需要移动指向开头,否则接下来读出无数据。
//system("echo you test >>1.txt");
int num_read=read(fd,buf_read,sizeof(buf_read));//从fd指向文件读取内容到buf_read.
if(-1==num_read)
{
perror("read");
return -1;
}
buf_read[num_read]='\0';//读取字符后面添加字符串结束字符'\0'
printf("read %d from %s to buf\n",num_read,argv[1]);
printf("the buf is: %s\n",buf_read);
close(fd);
return 0;
}
最后运行效果:
zdg@ubuntu:/mnt/hgfs/SHARE/3.文件系统$ ./a.out 1.txt
num_write=12
read 12 from 1.txt to buf
the buf is: hello world!