Re: [問題] I/O in C
※ 引述《dozer (rezod)》之銘言:
: 想要在一個用fopen打開的檔案中
: 插入一行字
: 比如說 原本的檔案長這樣
: first line
: second line
: @
: lastline
: 想要在@前面加入一行 third line, i.e.
: first line
: second line
: third line
: @
: lastline
: 有沒有除了全部讀到buffer裏面 再重新寫入之外的方法哩
: 因為那樣就不能處理很大的檔案了...
一次讀一行?不過這樣file I/O會很多...如下:
#include <stdio.h>
#include <stdlib.h>
//回傳此行幾個char,包括'\n'
static int getline( char *const str, FILE *fp)
{
int i = 1,c = 0;
while( (c = fgetc(fp)) != '\n' && c != EOF ){
str[(i++) -1] = c;
}
str[i - 1] = '\0';
return c == EOF ? 0:i;
}
int main()
{
FILE *fp = fopen("ooxx.txt","rt");
int i = 1;
while( i ){
char str[1024];
i = getline(str,fp);
if( str[0] == '@' ){
puts("Hello");
}
puts(str);
}
return 0;
}
然後再將輸出redirect到檔案即可。為了避免過多的file I/O,可以多讀幾行
再做一次輸出。
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 218.160.110.96
討論串 (同標題文章)
LinuxDev 近期熱門文章
PTT數位生活區 即時熱門文章