c實現功能(7)寫入和讀取文字檔案
阿新 • • 發佈:2018-12-13
#include <stdio.h> #include <string.h> int main() { //向一個檔案中寫入內容 char s[1024] = {0}; //開啟一個檔案 FILE *p = fopen("D:\\test\\a.txt","w"); //將資訊寫入到檔案中 while(1){ //將陣列的內容清0 memset(s,0,sizeof (s)); //scanf("%s",s); //這種方式無法輸入空格 gets(s); //設定輸入的退出模式 if(strcmp(s,"exit") == 0){ break; } //給每行新增換行符 int len = strlen(s); s[len] = '\n'; fputs(s,p); } //關閉檔案 fclose(p); printf("end\n"); return 0; }
#include <stdio.h> #include <string.h> int main(){ //從一個檔案中讀取內容 char s[1024] = {0}; //以只讀的方式開啟一個檔案 FILE *p = fopen("D:\\test\\a.txt","r"); //需要判斷是否到達檔案的末尾 while(!feof(p)){ //將陣列的內容清0 memset(s,0,sizeof (s)); fgets(s,sizeof (s),p); printf("%s\n",s); } fclose(p); return 0; }