1 建立文件與讀文件
直接上代碼真朗,代碼的目的也很簡單,如果沒有文件僧诚,則建立文件遮婶,而如果文件存在,則可以執(zhí)行文件的讀寫操作湖笨。我將文件命名為file.c:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char *argv[])
{
int fd;
int i =0;
int ret;
unsigned char buf[10];
fd = open("test.txt",O_RDWR | O_CREAT,S_IRUSR | S_IWUSR);
if(fd < 0){
printf("---open file error---\r\n");
return -1;
}
ret = write(fd,"fwjeofj",5);
printf("ret=%d\r\n",ret);
#if 1
close(fd);
fd = open("test.txt",O_RDONLY);
if(fd<0){
printf("---read file error---\r\n");
return -1;
}
#endif
memset(buf,0,sizeof(buf));
ret = read(fd,buf,10);
printf("read:%d\r\n",ret);
for(i = 0 ; i < 10 ; i ++){
printf("%c ",buf[i]);
}
printf("\r\nbuf=%s\r\n",buf);
return 0;
}
執(zhí)行編譯操作:
$ gcc file.c -o file
$ ./file
首先旗扑,無文件存在
執(zhí)行操作,文件存在
之后慈省,再進(jìn)行讀寫等等操作臀防,都不會報錯了。