fwrite does not write to file

1

I have this hex_editor.exe program in c that reads from a text file with this format:

065_066_067_097_098_099_013_010_049_050_051
052_053_054_013_010_065_114_114_111_122_032
121_032_108_101_099_104_101_013_010_100_111
013_010_013_010_119_104_105_108_101_

and then create a new file by writing the numbers from the text file to another file byte by byte

the code is this:

int main (int argc,char **argv)
{
    from_hex_file(argv[1],argv[2]);
}

void from_hex_file(char name[],char new_name[])
{
    FILE* hex_file,* new_file;
    unsigned char num;
    char str[4];

    hex_file=fopen(name,"r");
    new_file=fopen(new_name,"wb");
    if(hex_file==NULL||new_file==NULL)
    {
       if(hex_file==NULL)
          printf("error no se pudo abrir el archivo\n");
       if(new_file==NULL)
          printf("error no se pudo crear el archivo\n");
       system("pause");
       exit(EXIT_FAILURE);
    }
    else
    {
        while(EOF!=fscanf(hex_file,"%3[^\n_]%c*",str))
        {
            num=(int)strtol(str,(char **)NULL,10);
            fwrite(&num,sizeof(num),1,new_file);
        }
    }
fclose(new_file);
fclose(hex_file);

}

My problem is that when I run the program in cmd with:

hex_editor prueba.txt res.txt

I do not write anything to res.txt, I already make sure that fwrite is writing to check if it returned 1, I know that the problem has something to do with the buffer or fflush but can not know what it is

    
asked by Jose M 28.03.2018 в 18:15
source

1 answer

2

The source of the problem is not the fwrite() , but the scanf() previous, which does not read correctly the pattern you expect in the file.

To begin with it seems to have a typographical error, because the expression you have put:

%3[^\n_]%c*

is not syntactically correct, and the compiler complains that this fscanf() specifies two parameters in its format string (the %3... and the %c ), but then only receives one variable parameter to leave it. I suspect you wanted to say %*c instead of %c* . As it is, it gives a segfault when executed.

Anyway, even correcting the error before said, the program does not work correctly because once it reaches the last number, it keeps reading it again and again without detecting the EOF, in an infinite loop, and I can not understand very Well the why. I think it's because the last line of the file has both a _ and a \n after the number of three figures, but your expression reads only up to _ and \n remains unread, one and again.

The problem however is solved if you simplify the format string of fscanf() . At the end of the day, why should we specify that there should be three different characters of \n and _ followed? Just tell him to read three characters, without more, and ignore the next set of characters as long as \n or _ . So:

while(EOF!=fscanf(hex_file,"%3c%*[\n_]",str))

With this change the program executes without problems and the output is the desired one.

    
answered by 28.03.2018 / 18:50
source