Thread: Writing lines to a file

  1. #1
    Registered User
    Join Date
    Jun 2010
    Posts
    5

    Writing lines to a file

    what function would you use to write a line to a file?

    If instead of printf("hello") to the terminal, how would I get that into a file? I can do character by character, but the basic tutorial and even this book (The C Book — The Preprocessor) don't seem to deal with lines.

    I can use output>file in the command line since it's printed perfectly on the terminal, but I need a way for it to do it internally.

    **also, when I do ./a.out output>file, the file is created with the correct text, but the terminal also throws a segmentation error, it doesn't affect anything but it seems out of place, any ideas about that?
    Last edited by dlwjiang; 06-24-2010 at 12:24 AM.

  2. #2
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    fprintf(stdout, "hello World\n");
    Read printf family documentation (printf,fprintf,vfprintf,sprintf,...)

    Code:
    FILE *fout; // out file
    fout = fopen("eg.txt","w");    //read fopen() documentation
    if(fout == NULL) { //error opening file
      //handle it
    }
    fprintf(fout,"Hello World!\n");   // write to file
    fflush(fout);                // read doc
    
    // after you are done with the file
    fclose(fout);              // close the file, read doc for details

  3. #3
    The Autodidact Dante Wingates's Avatar
    Join Date
    Apr 2010
    Location
    Valhalla
    Posts
    56

    Thumbs up

    I can see your problem is solved but just as a comment... When you dont know something, you can always create a function that does what you need and then call it later everytime you need it.

    Sonner or later we all find something that cant be done by using some library function... Thats why I normally try to understand and recreate everything I use... Well if you start thinking like I do soon you will be willing to learn assembly language, but thats not a bad thing...

    If you know how to send a single char to a file, then you can recreate a function like fputs, and call it later...

  4. #4
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    Probably he hasn't even learned to use array, pointer or even function!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. Trouble writing to file using fwrite()
    By yougene in forum C Programming
    Replies: 4
    Last Post: 12-30-2008, 05:13 PM
  3. Inventory records
    By jsbeckton in forum C Programming
    Replies: 23
    Last Post: 06-28-2007, 04:14 AM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. Writing and modifying data in a file
    By Micko in forum C Programming
    Replies: 2
    Last Post: 02-17-2005, 03:42 AM