How to read the data in a file and print it and then copy the contents to a file?

This is a discussion on How to read the data in a file and print it and then copy the contents to a file? within the C Programming forums, part of the General Programming Boards category; Code: #include <stdio.h> #include <stdlib.h> int main (int argc, char *argv[]) { char buffer[256]; FILE * myfile; myfile = fopen("read.txt","r"); ...

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    33

    How to read the data in a file and print it and then copy the contents to a file?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main (int argc, char *argv[])
    {  
        char buffer[256];
        FILE * myfile;
        myfile = fopen("read.txt","r");
        while (feof(myfile)==0)
        {
           
            fgets(buffer,256,myfile);
            printf("%s",buffer);
           
            printf("%d", feof(myfile));
           
        }
        
        fclose(myfile);
    }
    Help please? I also got an error in printing wherein the data in read.txt is "Hello" newline "World" and my program prints world twice. D: help!

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Don't use feof() - it doesn't work the way you expect it works.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main (int argc, char *argv[])
    {  
        char buffer[256];
        FILE * myfile;
        myfile = fopen("read.txt","r");
        while ((fgets(buffer,256,myfile))!= NULL) {
            printf("%s",buffer);
                 
        }
        
        fclose(myfile);
    }
    printing the last line twice is unfortunately, the way that feof() works - and why it shouldn't be used, in general. Use the above.

  3. #3
    Registered User
    Join Date
    Feb 2013
    Posts
    33
    I see. thanks a lot!

  4. #4
    young grasshopper jwroblewski44's Avatar
    Join Date
    May 2012
    Location
    Where the sidewalk ends
    Posts
    294
    Use fputs() to write the data to the file.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. read contents of a text file into a struct
    By lemonwaffles in forum C++ Programming
    Replies: 2
    Last Post: 08-03-2009, 03:20 PM
  2. how can i read .RData contents in an executable file?
    By Masterx in forum C++ Programming
    Replies: 9
    Last Post: 03-30-2009, 10:07 AM
  3. Read and display contents from text file
    By spadez in forum C Programming
    Replies: 2
    Last Post: 02-03-2009, 03:25 PM
  4. copy data from one file to another
    By dallo07 in forum C Programming
    Replies: 49
    Last Post: 12-05-2008, 02:18 PM

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