Thread: Trouble with lesson 10 (File I/O)

  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    3

    Trouble with lesson 10 (File I/O)

    I copied and pasted the code, so I know there aren't any typos. I made sure the file name was correct, but the program just spits random, unreadable characters at me. Any ideas?

    Code:
    #include <fstream>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
      char str[10];
    
      //Creates an instance of ofstream, and opens example.txt
      ofstream a_file ( "F:\test.txt" );
      // Outputs to example.txt through a_file
      a_file<<"This text will now be inside of example.txt";
      // Close the file stream explicitly
      a_file.close();
      //Opens for reading the file
      ifstream b_file ( "F:\test.txt" );
      //Reads one string from the file
      b_file>> str;
      //Should output 'this'
      cout<< str <<"\n";
      cin.get();    // wait for a keypress
      // b_file is closed implicitly here
    }

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Possibly the problem is: whenever you put a \ in a quote, you need to double up to \\, as a single \ in C or C++ code means "treat the next character as a special character". In this case, the \t becomes a tab, and that's not a valid file-name. Since the filename is invalid, it doesn't actually open the file, and you can't write to an unopened file, nor can you read anything from it. So when you try to read back the string, it doesn't, and the uninitialized value of the string is displayed.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    May 2008
    Posts
    3
    Thanks! It works out fine now.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File transfer- the file sometimes not full transferred
    By shu_fei86 in forum C# Programming
    Replies: 13
    Last Post: 03-13-2009, 12:44 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. Subtle(?) File I/O Problem
    By cecomp64 in forum C Programming
    Replies: 9
    Last Post: 07-16-2008, 11:39 AM
  4. File I/O Question
    By Achy in forum C Programming
    Replies: 2
    Last Post: 11-18-2005, 12:09 AM
  5. Simple File encryption
    By caroundw5h in forum C Programming
    Replies: 2
    Last Post: 10-13-2004, 10:51 PM