c - Reading a file, modifiying each line, storing it into a buffer, printing all at once -


this file:

 line 1  line 2  line 3 

how read file line line...

append suffix each line..

file *fp = fopen ("file", "r"); while (fgets (buffer, sizeof (buffer), fp) != null) {      // append "test" each line.     // store result in buffer named "result"  } fclose (fp); 

print result @ once:

printf( "%s", result ); 

expected result :

 line 1test  line 2test  line 3test 

the below program might requirement not efficient enough. giving rough example. hope 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 assumption. dynamic size may decided  char **result = (char**)malloc(sizeof(char*)*10); // 10 assumption. dynamic size may 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 100 characters read 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; } 

Comments

Popular posts from this blog

Add new key value to json node in java -

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

javascript - Highcharts Synchronized charts with missing data points -