fread is reading too much

This is a discussion on fread is reading too much within the C Programming forums, part of the General Programming Boards category; Everyone says that you can use fread to input a structure, right? For some reason this code doesn't work and ...

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    46

    fread is reading too much

    Everyone says that you can use fread to input a structure, right? For some reason this code doesn't work and I can't figure out what I'm doing wrong.
    Code:
    #include <stdio.h>
    #include <string.h>
    
    struct Data
    {
        char name[20];
        int age;
    };
    
    int main()
    {
        FILE *IN;
        struct Data *DATA = malloc(sizeof(struct Data));
        memset (DATA->name, '\0', 80);
        if ((IN = fopen("readFrom.txt", "r")) == NULL) {
            puts("Input file could not be opened");
            exit(0);
        }
        fread(DATA, sizeof(struct Data), 1, IN);
        puts(DATA->name);
        printf ("%d\n", DATA->age);
        return 0;
    }
    When I run this it reads the whole name, the age, and a part of the name on the next line into just that one structure. I also figured that I needed to call free on DATA, but when I do I also get a debug error when I run the code. I've stepped through the code in my debugger and it looks like everything is being treated as a string and being placed in the 20 characters allocated for the array in the structure. Am I using fread wrong or is this all I can do?

    Any help would be most appreciated
    C code. C code run. Run code, run...please!

  2. #2
    train spotter
    Join Date
    Aug 2001
    Location
    near a computer
    Posts
    3,854
    >>if ((IN = fopen("readFrom.txt", "r")) == NULL) {

    may be opening in text mode use "rb" or play with the _fmode setting (_0_TEXT is default)

    ensure sizeof(struct data) is giving the correct size. Try sizeof(DATA).
    "Man alone suffers so excruciatingly in the world that he was compelled to invent laughter."
    Friedrich Nietzsche

    "I spent a lot of my money on booze, birds and fast cars......the rest I squandered."
    George Best

    "If you are going through hell....keep going."
    Winston Churchill

  3. #3
    Registered User
    Join Date
    Dec 2001
    Posts
    421
    Try sizeof(DATA)
    I dont think that will work... that'll most likely just give you the size of a pointer (ie. 4 bytes).

    It could be because of a compiler setting or something??

    in MSVC++ you can set the size of the "struct member alignment". one of the options in the drop down is 8 bytes... this i think is the default. now, i'm not sure if this is the case, but it might be that you have specified this option to be 8 bytes, and then both the name and the age variables inside the struct would be padded out (to 24 and 8 bytes respectively).

    maybe if you change your compiler setting to 4 bytes then you'll be fine??

    good luck
    U.
    Quidquid latine dictum sit, altum sonatur.
    Whatever is said in Latin sounds profound.

  4. #4
    train spotter
    Join Date
    Aug 2001
    Location
    near a computer
    Posts
    3,854
    Sorry, habit.
    [I declare struc as DATA, instance as Data, pointer a pData. (sizeof(DATA) in this case would be that of a pointer)]

    Size of the structure should be the same for reading and writting, regardless of padding. (I am assuming that you wrote the file) If not try recreating the file (rewritting a new one) as it may have gone 'bad'.
    "Man alone suffers so excruciatingly in the world that he was compelled to invent laughter."
    Friedrich Nietzsche

    "I spent a lot of my money on booze, birds and fast cars......the rest I squandered."
    George Best

    "If you are going through hell....keep going."
    Winston Churchill

  5. #5
    Banned Troll_King's Avatar
    Join Date
    Oct 2001
    Posts
    1,784
    Code:
    #include <stdio.h>
    #include <conio.h>
    #include <string.h>
    #include <stdlib.h>
    
    struct Data
    {
        char name[20];
        int age;
    };
    
    int main()
    {
        FILE *IN;
    	char buffer[256];
    	
    	system("cls");
    
        if ((IN = fopen("readFrom.txt", "r")) == NULL) {
            puts("Input file could not be opened");
            exit(0);
        }
    	//Get one line of text
    	fgets(buffer,256,IN);
    	buffer[strlen(buffer) - 1] = '\0';
    
    	//load your structure
    	struct Data *data = (struct Data*) malloc (sizeof(struct Data) *1);
    	sscanf(buffer,"%19[^\n]%3d", data->name, &data->age);
    	
    	//If you created the text file properly for example
    	//This is an example of the textfile. No this is no error. It 
    	//Has be be exactly 19 charcters before the number which is being
    	//scanned with 3 places in it. You have to know a lot about formatting
    	//to do this!
        //datafile looks like this (exactly):
    	//Has to be 19 charac343
    	printf("%s\n%d",data->name, data->age); _getch();
        //will print:
    	//Has to be 19 charac
    	//343
    
    	//Now write a record in binary form
    	FILE *fptr = fopen("readFrom.bin","wb");
    
    	fwrite(data,1,1,fptr);
    
        return 0;
    }
    Sorry, you probably won't understand this but I have to go to sleep so I can get up for work. You should work with a binary file or else go through something like the above.

  6. #6
    Registered User
    Join Date
    Nov 2001
    Posts
    46
    So that would be a no? Because I was using the same technique that another program I found while surfing used and it worked great. I don't understand why
    Code:
    struct _FuncInfo
    {    char name[20],	
          found[20],
          description[200];
    };
    
    struct _FuncInfo *Info = (_FuncInfo *)malloc(sizeof(_FuncInfo));
    FILE *fp;
    int size = sizeof (struct _FuncInfo);
    <snip>
    if((fp = fopen("c:\\funclist.txt", "r"))==NULL)
    <snip>
    while(fread((void *)Info,size, 1, fp)==1)
    C code. C code run. Run code, run...please!

  7. #7
    Banned Troll_King's Avatar
    Join Date
    Oct 2001
    Posts
    1,784
    It makes a difference what your datafile looks like and whether the fields are uniform. fread should be reserved for working on binary files because it will choke on certain text characters. You can use fgets to retrieve anything though.

    If a binary was created with a structure than using fread to fill that same structure afterward shouldn't be a problem. Infact it only takes about four or five lines of code. First find how many records there are than fill and array of structures with fread.

    In the code above I used fgets because a text file was being used rather than a binary file. Also fgets will retrieve one line of text than the sscanf will allow you to use delimiters representing a character by character reading of that line. That is a powerful way to read a textfile because you have complete control over every single character you read. If you have ever taken a Cobol course or seen a printer spacing chart than it might make more sense.

    The error that you were experiencing was that your char array was reading everything because it would read the first 19 characters, and than your integer was picking up garbage, and fread was probably choking on the newline character. I don't know what your datafile looked like however so it is hard to say for sure.

  8. #8
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,334
    > memset (DATA->name, '\0', 80);
    Er, name is only 20, so your program is broke already - you've just blasted 60 bytes of someone elses memory with zeros

    > if ((IN = fopen("readFrom.txt", "r")) == NULL)
    Be absolutely sure that this is or is not a text file.

    Text files are like your C source code, variable length lines with a newline at the end of each one, and every character on the line is intelligible.
    These you use fgets() for reading

    Binary files are like your program executable - lots of wierd and wonderful characters, which, if you load them into most text editors stand a good chance of crashing them.
    These you use fread() for reading

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 03-05-2009, 02:14 AM
  2. Replies: 7
    Last Post: 02-02-2009, 06:27 AM
  3. Reading from binary file; fread problems?
    By pmgeahan in forum C Programming
    Replies: 3
    Last Post: 01-15-2009, 04:07 PM
  4. reading words using fread
    By -EquinoX- in forum C Programming
    Replies: 22
    Last Post: 05-05-2008, 02:09 PM
  5. fread - reading strings and integers.
    By Vber in forum C Programming
    Replies: 1
    Last Post: 11-17-2002, 03:08 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21