Thread: simple File I/O question

  1. #1
    Registered User
    Join Date
    Aug 2003
    Posts
    12

    simple File I/O question

    Hello

    Below is a piece of code that opens a file.
    if I got readFile(fileName) where "fileName" is a string containing a file the program does not compile.


    Code:
    string fileName;
    fileName = "blah.txt";
    
    ifstream readFile;
    
    readFile.open(fileName);
    Code:
    ifstream readFile;
    
    readFile.open("blah.txt");
    if I enter the file name directly in quotes it works. How do I specify the file I want to open using a variable?

    I've of course #include 'ed string and fstream

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Try
    readFile.open( fileName.c_str() );
    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.

  3. #3
    Registered User
    Join Date
    Aug 2003
    Posts
    12
    thanks, just found out myself, learn the whole s string part and was a about to reply that I found a solution!

    Good to see I was on the right track

  4. #4
    Registered User
    Join Date
    Oct 2003
    Posts
    55
    Code:
    readFile.open( fileName.c_str() );
    what does the .c_str() do?

  5. #5
    Registered User PotitKing's Avatar
    Join Date
    Dec 2001
    Posts
    28

    c_str()

    The c_str() and data() methods of the string class, returns the string as an array of bytes, like "old" C strings.

    string s = "Hello";
    char *oldtypestring = s.c_str();

    oldtypestring is now "Hello\0"
    % gcc -v
    Configured with: FreeBSD/i386 system compiler
    Thread model: posix
    gcc version 3.3.3 [FreeBSD] 20031106

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A simple file I/O problem
    By eecoder in forum C Programming
    Replies: 10
    Last Post: 10-16-2010, 11:00 PM
  2. C++ File I/O question
    By zero_cool in forum C++ Programming
    Replies: 3
    Last Post: 08-16-2005, 10:43 AM
  3. File I/O question... please help!
    By sirSolarius in forum C++ Programming
    Replies: 11
    Last Post: 10-07-2003, 08:30 AM
  4. File I/O Question
    By DocDroopy in forum C Programming
    Replies: 4
    Last Post: 08-02-2002, 08:58 AM
  5. I have a file I/O question as well
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 11-29-2001, 04:11 PM