The editing of the C binary file is looped
You must replace every third number in the binary file with the same number with the opposite sign. The numbers are represented by the double type. When you try to overwrite a part of the file, it loops.
#include <stdio.h>
#include <stdlib.h>
#define MAX_PATH 261
int main (int argc, char *argv[])
{
FILE *input_file;
char *filename;
int n = 0;
double number;
filename = (char*) malloc (MAX_PATH*sizeof(char));
if (argc != 2)
{
printf ("Enter filename: ");
scanf ("%s", filename);
} else filename = argv[1];
if ((input_file = fopen (filename, "r+b")) == NULL)
{
perror ("Cannot open input file");
return 1;
}
while (!feof(input_file))
{
n += fread (&number, sizeof(double), 1, input_file);
if (n % 3 == 0 && n != 0)
{
number *= -1;
fseek (input_file, (n-1)*sizeof(double), SEEK_SET);
fwrite (&number, sizeof(double), 1, input_file);
}
}
fclose (input_file);
free (filename);
system ("pause");
return 0;
}
0
1 answers
For files open for update (those which include a "+" sign), on which both input and output operations are allowed, the stream shall be flushed (fflush) or repositioned (fseek, fsetpos, rewind) before a reading operation that follows a writing operation.
This requirement is not met in your program - after fwrite
, you need to call fseek
again.
2
Author: Alex F, 2019-12-19 07:01:06