Thread: Can't write into out.txt

  1. #1
    Registered User
    Join Date
    Jun 2016
    Posts
    16

    Can't write into out.txt

    This is a code I made that writes "Hello" to the file out.txt. However, when I open the file, it is blank. Is it because the file should not currently exist?

    insert
    Code:
    #include<stdio.h>
    main()
    {
        FILE *fout;
        
        fout = fopen ( "out.txt", "w");
        fprintf(fout, "Hello");
        fclose(fout);
    }

  2. #2
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,127
    Note the changes I made to your code:
    Code:
    #include <stdio.h>
    
    int main(void)
    {
       FILE *fout = NULL;
    
       fout = fopen( "out.txt", "w");
    
       /* Check here that the file was opened correctly */
    
       fprintf(fout, "Hello\n"); /* Add a newline char */
       fclose(fout);
    
       return 0;
    }
    The code compiles and runs correctly, but you should add code to insure the file was opened correctly before trying to write to it.

  3. #3
    Registered User
    Join Date
    Jun 2016
    Posts
    16
    Thank you. It worked.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 09-09-2014, 08:23 AM
  2. Write in txt...
    By Ervilha in forum C Programming
    Replies: 1
    Last Post: 10-07-2009, 12:18 PM
  3. write bmp
    By namespace::me in forum C++ Programming
    Replies: 18
    Last Post: 05-07-2007, 05:17 PM
  4. problem with fout.write: cannot write 0x0A (10 dec)
    By yvesdefrenne in forum C++ Programming
    Replies: 7
    Last Post: 05-23-2005, 12:53 PM

Tags for this Thread