按行讀寫檔案需要用到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); }