C語言讀/寫txt文件實例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE 1024
int main()
{
    //讀
 char buf[MAX_LINE];  /*緩衝區*/
 FILE *fp;            /*文件指針*/
 int len;             /*行字符個數*/

 //讀
 if((fp = fopen("test.txt","r")) == NULL)
 {
 perror("fail to read");
 exit (1) ;
 }
 while(fgets(buf,MAX_LINE,fp) != NULL)
 {
 len = strlen(buf);
 buf[len-1] = '\0';  /*去掉換行符*/
 printf("%s %d \n",buf,len - 1);
 }
//寫
 if((fp=fopen("write_txt.txt","wb"))==NULL)
	{
		printf("\nopen file Fail,close!");
		getchar();
		exit(1);
	}
	fputs("Hello world123",fp);
	fclose(fp);	
  return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章