Hello,
I am trying to copy the contents from file fp to fout using fread and fwrite only but it is not working. Please can someone help me figure out what i am doing wrong. The issue is with the void writeNewFile function.Thanks!
Code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 1024
typedef struct sample{
char *label;
int id;
float value;
}sample;
void readFile(char fname[],sample* Samples[]);
void writeNewFile(sample* Samples[],int i);
int main()
{
const int SIZE = 1024;
sample* Samples[SIZE];
int i;
for(i=0; i<SIZE; i++)
Samples[i]=NULL;
readFile("sample.txt",Samples);
for(i=0; Samples[i]!=NULL; i++)
{
printf("\nid: %d\tlabel:%s\tvalue:%0.1f",Samples[i]->id,Samples[i]->label,Samples[i]->value);
free(Samples[i]->label);
}
for(i=0; Samples[i]!=NULL; i++)
free(Samples[i]);
printf("\n");
return (0);
}
void readFile(char fname[], sample* Samples[])
{
FILE* fp=fopen(fname,"rb");
char buffer[1000] = "1+Sensor01+2.13\n";
char *temp,*label;
int c=0;
if(fp==NULL)
{
printf("Can't open file");
exit(0);
}
fread(buffer,sizeof(char),1000,fp);/*reads the content of file at a go to buffer*/
fclose(fp); /*closes the file*/
temp=strtok(buffer,",");
while(temp!=NULL)
{
Samples[c]=(sample *)malloc(sizeof(sample));
Samples[c]->id=atoi(temp);
label=strtok(NULL,",");
Samples[c]->label=(char *)malloc(sizeof(char)*strlen(label));
strcpy(Samples[c]->label,label);
temp=strtok(NULL,"\n");
Samples[c]->value=atof(temp);
temp=strtok(NULL,",");
c++;
}
}
void writeNewFile(sample* Samples[],int i)
{
FILE* fp=fopen("sample.txt","r");
char buffer[1000];
const int SIZE = 1024;
FILE* fout = fopen("newfile.b", "wb");
if (fout == NULL)
{
printf("\nfile.b could not be opened\n");
exit(1);
}
else
while( fread(buffer, sizeof(char), 1000, fp)==1)
{
for(i=0; i<SIZE; i++)
{
fwrite(&(Samples[i]->id), sizeof(int),1,fout);
fwrite(&(Samples[i]->value), sizeof(float),1,fout);
fwrite(&(Samples[i]->label), sizeof(char),strlen(Samples[i]->label),fout);
}
}
exit(1);
fclose(fp);
fclose(fout);
}
The issue is with the void writeNewFile function.