按行读写文件需要用到fputs和fgets函数,feof函数可以检测是否到文件末尾,如果是,返回一个非零值,如果没有达到末尾,返回零值。
#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!\naaaaaaa\nbbbbbbb\nccc"; if(fp==NULL) { printf("open file failure!"); exit(1); } else { fputs(text,fp); } fclose(fp); fp=fopen(filename,"r+"); if(fp==NULL) { printf("open file failure!"); exit(1); } char buff[1024]; while(!feof(fp)) { fgets(buff,1024,fp); printf("%s",buff); } fclose(fp); return(0); }