How to write in a file using fscanf and fprintf

This is a discussion on How to write in a file using fscanf and fprintf within the C Programming forums, part of the General Programming Boards category; Hello guys! I have a question concerning fscanf and fprintf I do: /* The format of the id.dat file is ...

  1. #1
    g_p
    g_p is offline
    Registered User
    Join Date
    Dec 2006
    Posts
    85

    Thumbs up How to write in a file using fscanf and fprintf

    Hello guys!

    I have a question concerning fscanf and fprintf

    I do:

    /* The format of the id.dat file is : e.g.
    1 David Jones
    2 Johan Smith
    3 Sarlot James
    etc...
    */


    Code:
    #include <stdio.h>
    
    int main() {
    
    int id;
    char fname[100];
    char lname[100];
    
    FILE * fp = fopen("id.dat","r");
    
    fscanf(fp,"%d %s %s",&id,fname,lname);
    
    while(!feof(fp)) {
    
              printf("%d %s %s\n",id,fname,lname);
              fscanf(fp,"%d %s %s",&id,fname,lname);
    
             /* Here it prints all the elements that are registered  in the file */
    }
           
    /* Now i want to place in the end of the file a new element e.g. 4 John Rino */
    /* I do: */
    
    
    fprintf(fp,"%d %s %s\n",4,"John","Rino");
    
    
    /* This particular line has to write sthg in the file */
    /* of course i have "fopened" the file using "r" read and it's not possible to write
    in the file, if I i use "w" it destroys everything in the id.dat file */
    /* What shall i do in order to write a new element at the end of he file using fprintf? */
    
    }         /* main */

    Thanks in advance








    }

  2. #2
    g_p
    g_p is offline
    Registered User
    Join Date
    Dec 2006
    Posts
    85
    Well hi again!

    I found it!

    I just have to place "a+" or "a+b" and not "r" in order to write at the end of the file

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,765
    > while(!feof(fp))
    while ( fscanf(fp,"&#37;d %s %s",&id,fname,lname) == 3 )
    achieves two things
    1 - it removes duplicated lines of code, so you no longer have to worry about keeping them in step.
    2 - it actually checks for success rather than blindly marching on. If the %d found a non-integer, your code would just lock up in an infinite loop.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    Quote Originally Posted by g_p View Post
    Well hi again!

    I found it!

    I just have to place "a+" or "a+b" and not "r" in order to write at the end of the file
    When switching from reading to writing or vise versa, you need to rewind() the file (or fseek() in it). I'm not sure if this applies to append mode or not, but just to be safe, you should rewind() the file anyway.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  5. #5
    g_p
    g_p is offline
    Registered User
    Join Date
    Dec 2006
    Posts
    85
    Well thanks,
    now i have a different problem.

    I have defined a function out of main and it tries to print some results in a specified file

    it is like :


    Code:
    void Print_in_File(FILE *source_file,FILE *target file) {
    
    
    /* I use fscanf in order to read the source_file -> this is fine :) */
    /* Then i use fprintf in order to write to the destination file using fprintf(target_file,"...","a")*/
    /* the problem is that the target_file is empty after the fprintf cause main cannot see the changes!!!*/
    /* What shall i do in order for the file to be modified out of main??*/
    
    }
    Thanks, in advance!

  6. #6
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    You can pass file pointers just like you have done. How do you think fprintf() works? It takes a FILE* as a parameter.

    I think this is what you're doing. You're writing data to target_file, and then reading that data in main(). Well, you should probably fflush() the file and then rewind() it if this is what you are doing. If it isn't, be more specific.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  7. #7
    g_p
    g_p is offline
    Registered User
    Join Date
    Dec 2006
    Posts
    85
    Well i if i try to return a FILE * pointer for the txt file, will i have the desired results?

    Well i have never used fflush and rewind and today i have to submit a project so it would be difficult for me to use these functions cause i'm not confident with them, if i had time i would use them


  8. #8
    g_p
    g_p is offline
    Registered User
    Join Date
    Dec 2006
    Posts
    85
    Well i if i try to return a FILE * pointer for the txt file, will i have the desired results?

    Actually i did that, but it didn't work!

  9. #9
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,048
    It won't work. You need to flush the file.

    It's not hard, seriously. You use rewind() to start from the beginning of the file, and call fflush() after you write anything to the file. Both of these functions take one parameter: the FILE* pointer to operate on.
    Code:
    #include <stdio.h>
    
    void print_names(FILE *fp) {
        char name[BUFSIZ];
        int x = 0;
    
        while(fgets(name, sizeof(name), fp)) {
            printf("&#37;3i: %s", ++x, name);
        }
    }
    
    int main() {
        FILE *fp = fopen("names.txt", "a+");
        char name[BUFSIZ];
    
        puts("Previous names:");
        print_names(fp);
    
        printf("\nEnter your name: ");
        fgets(name, sizeof(name), stdin);
        rewind(fp);
        fputs(name, fp);
        fflush(fp);
        rewind(fp);
    
        puts("Updated list of names:");
        print_names(fp);
    
        fclose(fp);
    
        return 0;
    }
    If you really don't feel like doing this, open the file for writing, write your data, close the file, then open the file for reading.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

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, 05:27 PM
  2. fscanf causes a SEGMENTATION FAULT
    By yougene in forum C Programming
    Replies: 15
    Last Post: 12-29-2008, 12:11 AM
  3. Using a file like Virtual Memory
    By firetheGlazer in forum C Programming
    Replies: 3
    Last Post: 07-01-2008, 05:44 PM
  4. sequential file program
    By needhelpbad in forum C Programming
    Replies: 80
    Last Post: 06-08-2008, 02:04 PM
  5. Multithreading problem
    By Bacardi34 in forum C Programming
    Replies: 5
    Last Post: 09-02-2004, 03:26 PM

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