Thread: Binary file read

  1. #1
    Registered User
    Join Date
    Sep 2013
    Location
    Jamaica
    Posts
    134

    Binary file read

    Well the program crashed when I run this code that I wrote. Can some1 point out my error please.

    Code:
    #include <stdio.h>
    
    struct person{
    	char firstName[15];
    	char lastName[10];
    	int age;
    	char address[35];
    	char gender;
    };
    
    
    int main(void)
    {
    	FILE *fPtr;
    	
    	struct person newPerson;
    	
    	if((fPtr = fopen("person.dat", "rb")) == NULL)
    	{
    		printf("File could not be opened.\n\n");
    	}
    	else
    	{
    		printf("%9s %11s %4s %8s %7s\n", "First Name", "Last Name", "Age", "Address", "Gender");
    		while(!feof(fPtr))
    		{
    			fseek(fPtr, sizeof(struct person)* -1, SEEK_SET);
    			fread(&newPerson, sizeof(struct person), 1, fPtr);
    			printf("%9s %11s %4d %8s %7s\n\n", newPerson.firstName, newPerson.lastName, newPerson.age, newPerson.address, newPerson.gender);
    		}
    		fclose(fPtr);
    	}
    	
    	getchar();
    	return 0;
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    You're using eof to control a loop. Don't do that. (Check the FAQ on the topic.)

    Also why are you continually using fseek? Why not just read through the file? And what is trying to use a negative offset to the beginning of the file even supposed to mean?

  3. #3
    Registered User
    Join Date
    Sep 2013
    Location
    Jamaica
    Posts
    134
    K i read the FAQ and get understand why the feof is wrong, now the fseek, I was just trying something. TY

  4. #4
    Registered User
    Join Date
    Jun 2010
    Location
    Michigan, USA
    Posts
    143
    What warnings are you getting when you compile? If none, increase the level of warnings you get.

    I am getting several warnings, but two seem to concern me.

    On the fseek call, why are you using a negative value for the second argument? What is the type of the second argument as called? What is the type of the fseek second argument as defined?

    On the last printf call, what is the type of the last argument in the format string? What is the type of the last argument passed to the printf call?

  5. #5
    Registered User
    Join Date
    Sep 2013
    Location
    Jamaica
    Posts
    134
    forget about the fseek, I was just trying to see if did something(it did nothing)I erased it I don't get any warning errors.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 12
    Last Post: 06-18-2012, 08:23 AM
  2. Binary read from file
    By dereach in forum C Programming
    Replies: 5
    Last Post: 02-27-2008, 03:34 PM
  3. Read binary file
    By Ken JS in forum C++ Programming
    Replies: 3
    Last Post: 05-29-2007, 11:12 AM
  4. Read a binary file
    By Sue Paterniti in forum C Programming
    Replies: 8
    Last Post: 04-29-2002, 02:36 AM