这次我们一同来完成一个小题目:
用C程序创建一个hello.txt的文件,然后写入Hello World,然后再读出来打印。
代码部分:
#include<stdio.h>
#include<sys/types.h>
#include<string.h>
#include<fcntl.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(){
char buf[40]; //用户用来储存读取文件的数据的数组
int fd=-1;//定义文件符
char *ms="hello world";
fd=open("2.txt",O_RDWR);
if(fd=-1){
printf("file is not exit\n");
fd=open("2.txt",O_RDWR|O_CREAT|O_TRUNC,664);
write(fd,ms,strlen(ms));
printf("create a sucess!\n");
lseek(fd, 0, SEEK_SET);
printf("start to read\n");
read(fd,buf,40);
printf("内容是%s\n",buf);
}
close(fd);
}
}
~
结果如下