Thread: writing a file with a variable as a filename?

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    2

    writing a file with a variable as a filename?

    I can get a file to write to a specific file name using the following code.

    Code:
            ofstream outfile("name.dat");
            outfile << username << endl;      
            outfile << age << endl;
            outfile.close();
    simple enough.
    But instead of it writing to a file "name.dat"
    I would like it to write to a file that is equivalent to the username.
    I've tried a few thigns like the following

    Code:
            ofstream outfile(username + ".dat");
            outfile << username << endl;      
            outfile << age << endl;
            outfile.close();
    But apparantly that doesn't follow the fstream rules. I've experimented with a whole bunch of other failed options apparantly I'm going about this the wrong way. Can someone give me some insight that might point me in the right direction.
    Muchly appreciated.

  2. #2
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,090
    It depends on how username is declared. If it is a string (i.e. from the standard string class in <string>) then you need to put it inside parentheses and use .c_str():
    Code:
    ofstream outfile((username + ".dat").c_str());
    If it is a C-style string (i.e. null terminated character array), then you can't add strings like that. You would need to use strcat in <cstring>:
    Code:
    char filename[100];
    strcpy(filename, username);
    strcat(filename, ".dat");
    ofstream outfile(filename);
    Because you didn't post the rest of your code, those examples might not work for you, but that is the idea.

  3. #3
    Registered User
    Join Date
    Sep 2004
    Posts
    2
    Thanks Jlou. Your suggestions helped alot.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need Help Fixing My C Program. Deals with File I/O
    By Matus in forum C Programming
    Replies: 7
    Last Post: 04-29-2008, 07:51 PM
  2. gcc link external library
    By spank in forum C Programming
    Replies: 6
    Last Post: 08-08-2007, 03:44 PM
  3. Not writing to a file.
    By sideshow_bob in forum C Programming
    Replies: 2
    Last Post: 02-19-2003, 11:25 AM
  4. what does this mean to you?
    By pkananen in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2002, 03:58 PM
  5. Variable Allocation in a simple operating system
    By awkeller in forum C Programming
    Replies: 1
    Last Post: 12-08-2001, 02:26 PM