Thread: FILE problem, again. Help!

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    3

    Question FILE problem, again. Help!

    Here's the problem. I open the non-text file, then what I want to do is to check how many entries saved I already have so that I know where I will save my next entry on the said file. Here's what I did:

    typedef structUserType arrUser[10];

    if ((pUser = fopen("file.dat", "wb")) != NULL)
    {
    while (fread (&aUser[i], sizeof(structUserType), 1, pUser))
    i++;
    //What this supposedly does it to check how many saved entries are already in the file. The condition will return a 0 if the pointer is at the eof already//

    scanf ("%s", aUser[i].strName);
    //Here lies the problem because it seems that the counter isn't moving. So when I do this://

    fwrite(&aUser[i], sizeof(structUserType), 1, pUser);

    it keeps on overwriting on that same array of structure. Help!!!
    So where did I go wrong? I'm stuck at this part forever!

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    28
    You can find out how many structures are on your file by using ftell() to get the number of bytes in your file and then divide that by the size of the structure ie:

    fseek(pUser, 0L, SEEK_END);
    temp = ftell(pUser);
    result = temp / sizeof(arruser);

    ftell returns a long int.

    just a thought but would it be better just to open the file in append mode when you want to add a new structure.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    3

    Talking thanks

    Ey, thanks! I'll try that one.

  4. #4
    train spotter
    Join Date
    Aug 2001
    Location
    near a computer
    Posts
    3,868
    You can also run a check on the file contents with

    iRemainder = temp % sizeof(structUserType);
    if(iRemainder!=0)
    {
    //error
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie homework help
    By fossage in forum C Programming
    Replies: 3
    Last Post: 04-30-2009, 04:27 PM
  2. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  3. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  4. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM
  5. Rename file problem
    By Emporio in forum C Programming
    Replies: 2
    Last Post: 06-05-2002, 09:36 AM