Thread: Binary files

  1. #1
    Registered User
    Join Date
    Oct 2019
    Posts
    11

    Binary files

    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.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,550
    You don't seem to call writeNewFile, so how do you know the issue is with that function?

    That said, that function does look wrong: why does it call fread when it looks like the intention is to write?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Oct 2019
    Posts
    11
    I didn't even realize not calling it. Thanks!!
    The function calls fread to get the the contents of the first file and uses fwrite to copy it to the new file

  4. #4
    Registered User
    Join Date
    Oct 2019
    Posts
    11
    Still, when I call the function it does not write the content in the new file.

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,550
    Quote Originally Posted by bab27
    The function calls fread to get the the contents of the first file and uses fwrite to copy it to the new file
    Then what's readFile for?

    No, a function should do one thing and do it well. I suggest renaming writeNewFile to writeSamples, and readFile to readSamples.

    Implement writeSamples to write an array of sample objects such that the sample objects already exist. Test that it works by creating sample objects by hand and calling writeSamples. I would expect a prototype like this:
    Code:
    int writeSamples(FILE *fp, const sample *sample_objs, size_t size);
    So, you handle the opening and closing of the file separately; writeSamples only has writing of sample objects as its focus. You can either return a boolean to indicate success or return an error code (document your choice and if the latter, use an enum to name the available error codes).

    Implement readSamples to read sample objects from a file. Test that it works by reading a file previously created by writeSamples, and checking to see if the resulting array of sample objects match the original array. There are several ways of designing the function, but here's one:
    Code:
    int readSamples(FILE *fp, sample **sample_objs, size_t *size);
    With this version, again the return value can either be boolean or an error code. sample_objs is now a pointer to a pointer because you will malloc a dynamic array of sample objects, and so you need to write that pointer to the caller, hence the pointer is "passed by reference" as a pointer to a pointer. The size of course needs to be a pointer as you have to update it with the number of elements in use (whereas you might allocate/reallocate a larger capacity than the size).

    Only when you have implemented and tested both of these separately do you combine them in a third function (could be the main function) that reads and writes by calling these two functions.

    If you prefer, you can also write a wrapper function for each of these that take a file name rather than a FILE pointer as the first argument. So, you handle the opening and closing of the file in the wrapper function, which then forwards the nitty gritty reading/writing work to readSamples/writeSamples. For reusability, you should not be hardcoding file names in these functions. You might hardcode them in the main function that calls these functions, or pull them out to be named constants that the main function uses.

    By the way, I'm a bit concerned about your use of fread and fwrite: why not just read and write as a text file? From what I see, your current readFile function uses fread to read a chunk of bytes, but then it goes on to use atoi and atof as if it were dealing with a text file. If you want to fwrite something, you need to fread it back since fwrite writes its underlying bytes, whereas atoi and atof converts a textual representation, not the underlying bytes. Or, if you do want to just read a chunk of bytes, then it's up to you to reinterpret the correct sequence of bytes as an int, float, etc, not try to convert them as if they constitute a textual representation.
    Last edited by laserlight; 11-29-2019 at 02:23 PM.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User
    Join Date
    Oct 2019
    Posts
    11
    Thanks a lot for the tips. Especially the fread and fwrite. I will try different codes using both ways and see how they work out.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. binary files: copying jpeg or video files
    By cfanatic in forum C Programming
    Replies: 5
    Last Post: 07-19-2012, 08:17 AM
  2. Binary files
    By Moony in forum C Programming
    Replies: 5
    Last Post: 06-28-2006, 01:23 AM
  3. Binary Files
    By Axpen in forum C Programming
    Replies: 14
    Last Post: 08-12-2004, 08:41 PM
  4. Binary files
    By Brian in forum C Programming
    Replies: 2
    Last Post: 02-18-2002, 01:13 PM
  5. binary files
    By face_master in forum C++ Programming
    Replies: 10
    Last Post: 11-12-2001, 01:00 AM

Tags for this Thread