对学习C语言而言,文件操作属于横向学习,而之前的指针属于纵向学习。所谓横向学习,就是快速掌握API,了解使用就行,纵向学习则不同,纵向学习需要深入地理解原理。但是在linux系统编程的学习中,文件操作属于纵向学习,因为在Linux设计哲学中是一切皆文件的思想。
第一个API函数,fopen
第二个API函数,fclose
在打开文件之后,不再操作文件了,都需要将文件流关闭。
eg:先实现创建并写入文件数据:
#include <stdio.h> #include<stdlib.h> int main() { FILE *fp; const char *filename="F:/mytest/mytext.txt"; fp=fopen(filename,"w"); char *text="i am a filetest!\r\n"; if(fp==NULL) { printf("open file failure!"); exit(1); } else { while(*text!='\0') fputc(*text++,fp); } fclose(fp); return(0); }
读出文件在终端显示:
#include <stdio.h> #include<stdlib.h> int main() { FILE *fp; const char *filename="F:/mytest/mytext.txt"; fp=fopen(filename,"r+"); char *text="i am a filetest!\r\n"; if(fp==NULL) { printf("open file failure!"); exit(1); } int ch=getc(fp); while(ch!=EOF) { printf("%c",ch); ch=getc(fp); } fclose(fp); return(0); }
读写综合:
#include <stdio.h> #include<stdlib.h> int main() { FILE *fp; const char *filename="F:/mytest/mytext.txt"; fp=fopen(filename,"w+"); char *text="i am a filetest!\r\n"; if(fp==NULL) { printf("open file failure!"); exit(1); } else { while(*text!='\0') fputc(*text++,fp); } fclose(fp); fp=fopen(filename,"r+"); if(fp==NULL) { printf("open file failure!"); exit(1); } int ch=getc(fp); while(ch!=EOF) { printf("%c",ch); ch=getc(fp); } fclose(fp); return(0); }
注意,写入文件之后,需要关闭文件流,再重新打开读入终端。在接fgetc的时候,我用的int ch,因为C语言中,char就是int的数值,可以通过sizeof(‘a’)的结果看出,一个字符的sizeof大小为int 的大小。c++中则不再是这样。注意在指定文件路径的时候,请使用'/'符号而不是'\'符号,因为左斜杠在Windows和Linux上通用,而且更好用,Windows再设计的时候什么都和Linux反着来,但这里Windows采用'\'表示路径实为一个纰漏,因为这会和转义字符混淆,所以使用'\'的时候,上面的路径要改为F:\\mytest\\mytext.txt 要表示一个'\',在字符串中必须在'\'前再加一个'\'。