C语言中对文件操作主要有open,write,read三个函数,最近复习到这几个函数,故顺便写了一个demo回顾回顾。
#include <stdio>
#include <fcntl.h>
#include <io.h>
int main(int argc, char *argv[])
{
int fd,ret;
char content[]="this is test word",buf[1024];
fd=open("C:\\Users\\yxx\\Desktop\\test.txt",O_CREAT|O_WRONLY);
if(fd==-1)
{
printf("open failure\n");
return -1;
}
ret=write(fd,content,sizeof(content));
if(n==-1)
{
printf("write failure\n");
close(fd);
return -1;
}
close(fd);
fd=open("C:\\Users\\yxx\\Desktop\\test.txt",O_RDONLY);
ret=read(fd,buf,sizeof(buf));
if(ret==-1)
{
printf("read failure\n");
close(fd);
return -1;
}
close(fd);
printf("%s\n",buf);
return 1;
}
C语言中对文件操作还有三个很类似的函数,fopen,fwrite,fread三个函数,我也写了一个demo
#include <stdio>
int main()
{
FILE *fp;
fp=fopen("test.txt","w+");
char buf[]="this is test word";
if(fp==NULL)
{
printf("open failure");
return -1;
}
fwrite(buf,sizeof(buf),1,fp);
fclose(fp);
fp=fopen("test.txt","r+");
char content[1024];
if(fp==NULL)
{
printf("open failure");
return -1;
}
fread(content,sizeof(content),1,fp);
fclose(fp);
printf("%s\n",content);
return 1;
}
如果想了解更多文件操作的函数,可以访问http://see.xidian.edu.cn/cpp/html/238.html