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;
}