fgets and fprintf. Is there a better way?


The following code WORKS.
It modifies an existing file by prefixing a line number to
it. This is for further processing of the newly formatted
file. It uses a while loop to process ONE LINE AT A TIME.
on and on and on.......

Is there a BETTER way? Is there a way whereby I don't
hear my hard drive whirling away? I thought of a buffer,
but in order to process a file 600 lines long, it would
need to be a HUGE buffer.

Here it is. . . . . . . .

int main(void)
      /* Pointers to input/output stream of type FILE. */

 FILE *infp, *output_file;

 char i_file_name[MAX_FILENAME_ARRAY], file_buffer[MAXARRAY];
 char out_file_name[MAX_FILENAME_ARRAY];
 int line_num = 1;

 /* Get the complete path name and file name in both cases. */

 printf("Please enter a file name for processing.\n");
 scanf("%s", i_file_name);

 printf("Please enter an output file name where a formatted '%s' will be written \n", i_file_name);
 scanf("%s", out_file_name);

 /* Open input file. Test for good file name. */

 if ((infp = fopen(i_file_name,"r")) == NULL) {
     printf("Error in input file name : '%s'\n",i_file_name);
     return 0;    /* Stop processing. */

 while( fgets(file_buffer,MAXARRAY , infp) != NULL )

     printf("%d %s",line_num, file_buffer);

     output_file = fopen( out_file_name , "a+");

     fprintf(output_file, "%d %s", line_num, file_buffer);

 }  /* End while. */

 return 0;

} /* End main. */

Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

SlartiConnect With a Mentor Commented:
There is a better way. It involves, as you suggested, a buffer. The key point is that you don't have to load the entire file into memory. What you do is:

1. Allocate a buffer of as much size as you can afford (10K should be no problem even in a large program, and if there's nothing else you're doing at the same time you should have no problem allocating even 200K).

2. Read as much of the file as will fit into the buffer, using the fread() statement.

3. Process the memory copy of the file, writing results to another memory buffer which you must also allocate. The second buffer should be slightly bigger to allow for the line numbers.

4. Write the new buffer into the output file using fwrite().

5. Repeat steps 2-4 until EOF is reached.

Granted, this will be a longer code than your method, but it will work MUCH more quickly, since in most cases you'll only do one read and one write.

If you want me to write the code for you you'll have to increase the question to at least 150 points.
Can you please clarify what you mean in answer number 3 in your answers.
All Courses

From novice to tech pro — start learning today.