Reputation: 33
I have the following task: I have a file (card) with 5 strings:
U98_25984nhdrwedb \n
U98_5647BGFREdand \n
U98_30984bgtjfYTs \n
U77_76498375nnnnn \n
U98_83645bscdrTRF \n
I need to extract to another file image.txt
those strings starting with "U9"
.
The below code without the memory assignment (malloc, calloc) print out the codes correctly to the screen, but it does not print the correct data to the image.txt
, where I only get "98_25984nhdrwedb@"
.
I think I am applying the memory allocation incorrectly, but when I use malloc
or calloc
(before the while loop) it gets worse and print out garbage and I cannot figure out how to set this correctly.
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <stdint.h>
typedef uint8_t BYTE;
int main()
{
FILE *input_card = fopen("card","r"); //open the file for reding
BYTE data[18];
int i, n = 5;
FILE* output = fopen("image.txt","w"); //open the output file for writing
output = malloc(sizeof(data)*18); //assign memory
while (!feof(input_card))
{
for (i = 1; i <= n; i++)
{
fread(data,sizeof(BYTE),18,input_card);
if(data[i] != 0)
{
if (data[0] == 'U' && data[1] == '9')
{
printf("data: %s",data);
fwrite(&data[i],sizeof(BYTE),18,output);
}
fclose(output);
}
}
}
fclose(input_card);
free(output);
return 0;
}
Upvotes: 1
Views: 282
Reputation: 136
In the following 2 lines from your code, the second line is incorrect:
FILE* output = fopen("image.txt","w"); //open the output file for writing
output = malloc(sizeof(data)*18); //assign memory <= This is WRONG
The variable output
is a FILE
pointer. You should not allocate it using malloc
. You should only use it if fopen
returns it successfully, which means it has already been allocated by fopen
.
This means you don't need this:
free(output); // This is also WRONG
Because this already freed the pointer's allocated data:
fclose(output);
Upvotes: 2
Reputation: 51
fopen() returns a FILE pointer so when you try to allocate memory (using malloc, that also returns a pointer) you're replacing the pointer to the FILE with something that points to memory instead of the file. Removing
output = malloc(sizeof(data)*18); //assign memory
should make it just work.
Upvotes: 2