[英]Reading a file, modifiying each line, storing it into a buffer, printing all at once
This is the file: 这是文件:
line 1
line 2
line 3
How to read the file line by line... 如何逐行读取文件...
Append a suffix to each line.. 在每行后面添加一个后缀。
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);
print the result all at once: 一次打印所有结果:
printf( "%s", result );
Expected result : 预期结果 :
line 1test
line 2test
line 3test
The below program might do the requirement but it is not efficient enough. 下面的程序可能满足要求,但效率不够。 I am just giving a rough example.
我只是举一个粗糙的例子。 Hope this helps.
希望这可以帮助。
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.