關於c語言中文字檔案的逐行讀取的實現

時間 2021-12-20 03:15:40

1樓:小夏在深圳

若檔案不存在,則會建立該檔案,如果檔案存在,寫入的資料會被加到檔案尾,即檔案原先的內容會被保留。

以附加方式開啟可讀寫的檔案。若檔案不存在,則會建立該檔案,如果檔案存在,寫入的資料會被加到檔案尾後,即檔案原先的內容會被保留。

#include

main()

file * fp;

fp=fopen(「noexist」,」a+」);

if(fp= =null) return;

fclose(fp);

擴充套件資料

1、如果輸入文字每行中沒有空格,則line在輸入文字中按換行符分隔符迴圈取值。

2、如果輸入文字中包括空格或製表符,則不是換行讀取,line在輸入文字中按空格分隔符或製表符或換行符特環取值。

3、可以通過把ifs設定為換行符來達到逐行讀取的功能。

2樓:

char *fgets(char *buf, int bufsize, file *stream);

成功,則返回第一個引數buf;否則返回null

例子:#include

#include

#include

#include

#define file_path "/home/tmp/test/test.txt"

#define buff_len 256

int main()

file *fp = null;

char *file = file_path;

char *line = (char *)malloc(buff_len * sizeof(char));//和c++不同的是,事先要申請空間,否則報段錯誤

if( (0 != access(file,r_ok|f_ok)) || (null==(fp=fopen(file,"r"))) )

printf("open %s failed\n",file);

return -1;

while( fgets(line, buff_len, fp) != null )//逐行讀取資料

printf("the content of each line is:\n%s",line);

if(fp!=null)

fclose(fp);

return 0;

擴充套件資料

c++逐行讀取txt檔案中的字串

#include

#include

intmain()

charsztest[1000]=;

intlen=0;

file*fp=fopen("1.txt","r");

if(null==fp)

printf("failedtoopendos.txt\n");

return1;

while(!feof(fp))

memset(sztest,0,sizeof(sztest));

fgets(sztest,sizeof(sztest)-1,fp);//包含了換行符

printf("%s",sztest);

fclose(fp);

printf("\n");

return0;

3樓:吉祥二進位制

#include

#include

#define line 1024

char *readdata(file *fp, char *buf)

void someprocess(char *buf)int main()

buf=(char*)malloc(line*sizeof(char));

while(1)

return 0;

}程式執行效果與1.txt的內容顯示完全一致。

4樓:萇賓

#include

int readdata(void)

rc=0;

i=0;

while ((get = fgetc(fp)) != eof)rc++;

}return i;

}int main()

5樓:樂正涵柳

當讀到換行符的時候就表示一行結束了

6樓:匿名使用者

#include

#include

#define buffer_size 100int main()

char temp[buffer_size]=;//臨時陣列,用來儲存前一次讀取的行

while(fgets(buffer,buffer_size,fp)!=null)

printf("%s\n",buffer);

strcpy(temp,buffer);

}fclose(fp);

return 0;}

c語言中,怎麼從文字中逐行讀取資料並賦值給不同變數

7樓:潮範君

給你簡單寫個框架吧,比如你要讀取的檔名為 test.txtfile *fp;

fp = fopen("test.txt","r");

int a;

fscanf(fp,"%d",&a);  //這樣就讀取到1個數字了,並賦值給a 你檔案格式就設定為一行1個數字

fclose(fp);

//這是個簡單的例子,你可以借鑑下,祝順利

c語言逐行讀取txt中的資料,並儲存到陣列中

8樓:匿名使用者

#include

int main(void)

fclose(fin);

/*此時已經讀取完畢,可以進行接下來的處理了*/return 0;}

求c語言讀取寫入文字檔案的函式實現

go陌小潔 c語言標準庫提供了一系列檔案i o函式用於檔案操作,比如fopen 用於開啟檔案 fread fwrite 用於讀寫檔案 fseek 用於設定操作位置等等,一般c語言教程上都有檔案i o一章,細緻內容,可以找本教科書學習一下。下面的示例,是向名為1.txt的檔案附加hello world...

c中如何讀取文字檔案的最後一行

兩種方法 一行一行讀,讀到檔案尾,你就知道哪行是最好一行了。可以考慮使用system.io.file.readalllines 方法,返回值是字串陣列。file.readalllines 方法 system.io https 從流的末尾一個位元組一個位元組往前讀,讀到換行符以後,再從這個位置讀到檔案...

python 讀取文字檔案 刪除裡邊的空行

趣園藝 def delblankline infile,outfile delete blanklines of infile infp open infile,r outfp open outfile,w lines infp.readlines for li in lines if li.spl...