打开文件的函数有fopen和open,这里的区别在于,fopen是c库中的函数,open是系统的函数,fopen位于stdio.h中,open需要添加多个头文件
fopen的使用
#include<stdio.h>
int main()
{
FILE *fp;
int c;
fp = fopen("file.txt", "w+");
fprintf(fp, "%s %s %s %d", "We", "are", "in", 2020);
fclose(fp);
fp = fopen("file.txt", "r");
while(1) {
c = fgetc(fp);
if(feof(fp)){
break;
}
printf("%c", c);
}
fclose(fp);
return 0;
}
open的使用
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main()
{
int fp, size;
char buf[20];
char buf1[] = "open write new";
fp = open("file.txt", O_RDWR);
if(-1 == fp)
printf("open file failed\n");
size = read(fp, buf, 20);
printf("%s\n", buf);
close(fp);
fp = open("file.txt", O_RDWR|O_APPEND);
if(-1 == fp)
printf("open file failed\n");
size = write(fp, buf1, sizeof(buf1));
printf("write %d to file\n", size);
}