读取文件,修改每一行,将其存储到缓冲区,一次打印

时间:2017-07-28 06:37:48

标签: c file-io

这是文件:

 line 1
 line 2
 line 3

如何逐行阅读文件......

为每一行附加后缀..

FILE *fp = fopen ("file", "r");
while (fgets (buffer, sizeof (buffer), fp) != NULL) {

    // append "test" to each line.
    // store the result in a buffer named "result"

}
fclose (fp);

一次打印结果:

printf( "%s", result );

预期结果:

 line 1test
 line 2test
 line 3test

1 个答案:

答案 0 :(得分:0)

以下程序可能会满足要求,但效率不高。我只是举一个粗略的例子。希望这可以帮助。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void display(char** temp,int LinesWritten);

int main()
{
FILE *fp;

char *buffer  = (char*)malloc(sizeof(char)*101); // 101 is just an assumption. dynamic size may be decided 
char **result = (char**)malloc(sizeof(char*)*10); // 10 is just an assumption. dynamic size may be decided
int LinesWritten = 0;
char **temp = result;
char **freetemp = result;

if((fp = fopen("file.txt","r"))==NULL)
{
        printf("Error while opening file\n");
        exit(1);
}

while((fgets(buffer,100,fp))&&(!(feof(fp))))     //assuming that 100 characters will be read into the buffer
{
        if(*result = (char*)malloc(sizeof(char)*10))
        {
                sprintf(*result,"%s%s",buffer,"test");
                *result++;
                LinesWritten++;
        }
}

fclose(fp);

display(temp,LinesWritten);

if(freetemp!=NULL)
{
        free(freetemp);
}

return 0;

}

void display(char** temp,int LinesWritten)
{

for(int i=0;i<LinesWritten;i++)
{
        printf("%s\n",*temp);
        *temp++;
}

return;
}