Thread: My C Programming Files I/O are not working

  1. #16
    Registered User
    Join Date
    Dec 2017
    Posts
    20
    i have looked at both codes. but unfortunately its a little bit too complicated for a beginner like me


    i was wondering is there any possibility with my current code at hand that there is a simple code solution
    So that instead of my code showing this:


    Varunummer: Namn Lagersaldo
    ————————————————————————————————————————————— —————
    0 0
    0 0
    0 0
    0 0
    0 0
    0 0

    it will show this instead:

    Varunummer: Namn Lagersaldo
    ————————————————————————————————————————————— —————
    123 majs 12
    234 banan 45
    432 klossar 32
    654 klas 32
    435 soppa 32
    121 granat 23



    Code:
    void readFromFile(char file[], int *antal_varor, struct storagemanipulation *inventory)
    {
        int i;
        printf("Enter the name of the file that you would like to open: \n");
        scanf("%s", file);
        char namn[30];
        int lagersaldo, varunummer;
        FILE *fp;
        fp=fopen(file,"r");
        if (fp!=NULL)
        {
            
            fscanf(fp, "%d\n", antal_varor);
            
            for (int i = 0; i < *antal_varor; i++)
            {
                if(fscanf(fp, file, "%s %d %d", inventory[i].namn, &inventory[i].lagersaldo, &inventory[i].varunummer) == 3)
                {
                    inventory[i].varunummer = varunummer;
                    strcpy(inventory[i].namn, namn);
                    inventory[i].lagersaldo = lagersaldo;
                }
            }
    }
        else
        {
            printf("no access to the File\n");
                }
        fclose(fp);
    }

  2. #17
    Registered User
    Join Date
    Dec 2017
    Posts
    1,136
    Quote Originally Posted by abmoh View Post
    i have looked at both codes. but unfortunately its a little bit too complicated for a beginner like me
    It's good you are not using it since it is riddled with errors and bad style.
    The best argument against democracy is a five minute conversation with the average voter. - Churchill

  3. #18
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,345
    Quote Originally Posted by abmoh
    So that instead of my code showing this:
    That's (probably) because you have a bug in your code concerning fscanf. Your compiler might be warning you about it; if not, you could try increasing the warning level. Either way, if you run the code with the debugging statements I added, you should see that there are plenty of unexpected read failures. Do you see that?

    Your compiler should also be warning you about these lines:
    Code:
    inventory[i].varunummer = varunummer;
    strcpy(inventory[i].namn, namn);
    inventory[i].lagersaldo = lagersaldo;
    I hinted that you should remove them because not only are they useless (the assignment to the values of inventory[i] should have been performed by the fscanf), but they are harmful: you are trying to reassign values to inventory[i], but you are using variables that have not even been initialised! Luckily, these lines probably never get executed because the fscanf call always fails.
    Last edited by laserlight; 12-15-2017 at 09:50 AM.
    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

  4. #19
    Registered User
    Join Date
    Dec 2017
    Posts
    20
    I did not try to run the code since i did not understand it. i have a deadline that soon expires and my teacher wants me to fix the issue.
    Everything seems to work except for the fact that i cant see my inputs. what i see instead is

    code showing this:


    Varunummer: Namn Lagersaldo
    ————————————————————————————————————————————— —————
    0 0
    0 0
    0 0
    0 0
    0 0
    0 0

    I want my code to become like this:

    Varunummer: Namn Lagersaldo
    ————————————————————————————————————————————— —————
    123 majs 12
    234 banan 45
    432 klossar 32
    654 klas 32
    435 soppa 32
    121 granat 23


    my current code is :

    Code:
    void readFromFile(char file[], int *antal_varor, struct storagemanipulation *inventory)
    {
        int i;
        printf("Enter the name of the file that you would like to open: \n");
        scanf("%s", file);
        char namn[30];
        int lagersaldo, varunummer;
        FILE *fp;
        fp=fopen(file,"r");
        
        if (fp!=NULL)
        {
            
            fscanf(fp, "%d\n", antal_varor);
            
            for (int i = 0; i < *antal_varor; i++)
            {
                if(fscanf(fp, file, "%s %d %d", inventory[i].namn, &inventory[i].lagersaldo, &inventory[i].varunummer) == 3)
                {
                    inventory[*antal_varor].varunummer = varunummer;
                    strcpy(inventory[i].namn, namn);
                    inventory[i].lagersaldo = lagersaldo;
                }
            }
    }
        else
        {
            printf("no access to the File\n");
                }
        fclose(fp);
    }

  5. #20
    Registered User
    Join Date
    Dec 2017
    Posts
    1,136
    Why are you not taking any of the advice being given to you? You need to read what I and (especially) laserlight have told you and make the indicated changes.
    The best argument against democracy is a five minute conversation with the average voter. - Churchill

  6. #21
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,345
    Quote Originally Posted by abmoh
    I did not try to run the code since i did not understand it.
    JUST RUN IT! You might understand it after you see it.

    Sigh, nevermind. This is wrong:
    Code:
    if(fscanf(fp, file, "%s %d %d", inventory[i].namn, &inventory[i].lagersaldo, &inventory[i].varunummer) == 3)
    It is wrong because you provided an extra argument, i.e., the argument named file. fscanf's first parameter is the FILE pointer, which you provided correctly. The second parameter is the format string, but you provided the format string as the third argument instead.

    As for those three lines: if you don't remove them, your code won't work, and I already explained why. If you really don't understand why, that's great: leave them there and see the problematic result, then you'll understand why.
    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

  7. #22
    Banned
    Join Date
    Aug 2017
    Posts
    861
    if you take a good look at this you may see what LaserLight is speaking about in the usage of fscanf it has a specif set of rules that the format of the function in the parameters of the function for it to be matched in order for that function to work, just like the functions you wrote will not work if you do not follow that same format you wrote them to work. it all applies across the board.

    C library function fscanf()
    Last edited by userxbw; 12-15-2017 at 10:22 AM.

  8. #23
    Banned
    Join Date
    Aug 2017
    Posts
    861
    Take a good hard look at how fscanf is being used without the 'file' included in it.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
     
    struct storagemanipulation
    {
        char namn[100];
        int lagersaldo;
        int varunummer;
         
    };
    // pass opened file into function for reading into struct array
    int readFromFile(FILE *fp, int antal_varor, struct storagemanipulation *inventory)
    {
        int i = 0;
         for ( ; i < antal_varor; i++)
            fscanf(fp,"%s%d%d",inventory[i].namn, &inventory[i].lagersaldo, &inventory[i].varunummer);
           
      // actually size gotten, it cannot over ride passed in size to get. 
      // so a means to actaully know how many records needed to be allowed
      //for is needed, or malloc to make extra space if it goes over given size
      return i; 
    }
       
    void saveToFile(FILE *fp, int antal_varor, struct storagemanipulation *inventory)
    {    //make sure it is set to 
        //end of file before writing to it, 
        //to prevent over writing of data.
        
        fseek(fp, 0, SEEK_END);
        
        for (int i = 0; i < antal_varor; i++)
            fprintf(fp, "%s %d %d\n", inventory[i].namn, inventory[i].lagersaldo, inventory[i].varunummer);
            
    }
     
     
    int main (void)
    {
        struct storagemanipulation inventory[4];
        char file[30], buffer[1024], name[100];
        int count = 0, size;
        FILE *fp;
         
         //gets user speified file name;
        printf("Enter filename\n");
        scanf(" %s", file);
         
         
         //Open for append; open 
         //(or create if the file does not exist) 
         //for update at the end of the file.
        if ((fp=fopen(file,"a+") ) == NULL )
              
             {
                printf("cannot create file\n");
               exit(1);
            }
              
            // check to see if file is empty
            // for first open if it is a fresh file. 
            // just to play it safe.
             
            fseek (fp, 0, SEEK_END); // go to end of file
            size = ftell(fp); // get size
     
     
            // put back to front of file just in case
            // that part all depends on how your file is, if it is a new file,
            //already has information in it, and you do not want to over write it
            // then you'll need to set it accordingly. 
     
                    fseek(fp,0,SEEK_SET);
             
            if ( size == 0 )
            {
                printf("File is empty\n"
                "please add data to file\n");
                             
                while ( count < 4)
                {    
                     
                    printf("enter name, item nuber, and number\n");
                     
                     
                    fgets(buffer, sizeof buffer, stdin);
                        scanf(" %s%d%d", strcpy(inventory[count].namn,name), &inventory[count].lagersaldo,
                        &inventory[count].varunummer);
                    count++;
                  
                }        
              
            }
            else
            readFromFile(fp, 4, inventory);
             
            if ( size > 0)
            {
                // size_t instead of int
                // for poratabiltiy, because sizeof/sizeof returns 
                // long int on linux, and I've been told it 
                // can retrun a different data type on others
                // so size_t takes care of that. 
                size_t check = 0;
                 
                //              returns actual size of array
                while ( check < sizeof(inventory)/sizeof(inventory[0]) )
                {
                    printf("Varunummer: Namn %s\nLagersaldo %d varunummer %d\n",inventory[count].namn , inventory[count].lagersaldo, inventory[count].varunummer);
                    check++;
                }
            }
            else
            {
                saveToFile(fp, 4, inventory);
                
                for ( int f = 0; f < 4; f++)
                    printf("%s %d %d\n",  inventory[f].namn, inventory[f].lagersaldo,
                        inventory[f].varunummer);
            }
             
          
           fclose(fp);
            return 0;
     }

    results
    Code:
    userx@slackwhere:~/bin
    $ ./temp2
    Enter filename
    filedata
    Varunummer: Namn name1
    Lagersaldo 10 varunummer 10
    Varunummer: Namn name1
    Lagersaldo 10 varunummer 10
    Varunummer: Namn name1
    Lagersaldo 10 varunummer 10
    Varunummer: Namn name1
    Lagersaldo 10 varunummer 10
    userx@slackwhere:~/bin
    $ ./temp2
    Enter filename
    filedata1
    File is empty
    please add data to file
    enter name, item nuber, and number
    name30 30 30 
    enter name, item nuber, and number
    mane40 40 40 
    enter name, item nuber, and number
    mane50 50 50 
    enter name, item nuber, and number
    mane60 60 60
    
    name30 30 30
    mane40 40 40
    mane50 50 50
    mane60 60 60
    userx@slackwhere:~/bin
    $
    Last edited by userxbw; 12-15-2017 at 12:46 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Working with files v2
    By Khabz in forum C++ Programming
    Replies: 5
    Last Post: 04-20-2013, 02:22 PM
  2. Working with files
    By Khabz in forum C++ Programming
    Replies: 15
    Last Post: 04-14-2013, 06:22 AM
  3. Replies: 4
    Last Post: 12-11-2011, 04:25 PM
  4. working with C files
    By Max^Power in forum C Programming
    Replies: 5
    Last Post: 07-07-2006, 06:02 PM
  5. Working with files in C
    By fmchrist in forum C++ Programming
    Replies: 2
    Last Post: 12-27-2005, 02:28 PM

Tags for this Thread