Writing to file in c++
Results 1 to 5 of 5

Thread: Writing to file in c++

  1. #1
    Senior Member
    Join Date
    Nov 2001
    Posts
    4,786

    Writing to file in c++

    When trying to teaching myself c++, I found the toughest thing to find information on, was the simple task of writing to a file. Just about every ‘beginning tutorial” on the subject seems to pass right over this subject.

    Athough it may have been covered in another tut here, the site was down and I was bored so I couldn’t check and needed something to do. But I think it deserves a little space of its own anyway.

    To output to a file its necessary to use fstream.h in addition to iostream.h, all the stream definitions are defined in fstream.h, as the name implies:

    #include < iostream.h>
    #include < fstream.h>

    To write to a file we must first open a file stream:
    // declare an output stream
    ofstream out1;

    this declares ‘out1’ to be of type ofstream or Output FileStream.

    // specify an output location
    out1.open("c:\\results.txt", ios::ate);

    this uses out1 to open a filestream to results.txt. (which must already exist)

    I’d like to point a couple of thing out here.

    The character ‘\’ is always used as an escape character so in order to write the path for a file in you must use ‘\\’. Otherwise the compiler will just see the escape character and assume the next character is the type of escape. So if you wrote the string in “c:\taxstuff” the compiler would see ‘c: <tab> axstuff.

    Id also like to point out ‘ios::ate’. This states the manner in which you would like to open the file. That is create, open and clear, append, etc. heres a list:

    ios::in Open for reading.
    ios::out Open for writing.
    ios::ate Position to the end-of-file.
    ios::app Open the file in append mode.
    ios::trunc Truncate the file on open.
    ios::nocreate Do not attempt to create the file if it
    does not exist.
    ios::noreplace Cause the open to fail if the file exists.
    ios::translate Convert CR/LF to newline on input and
    vice versa on output.

    These can be combined with the bit-or character ‘|’ like this:

    ios::in | ios::nocreate
    open if file if it exists do not create one

    ios::out | ios::noreplace open new file for output, fail if file exists

    ios::out | ios::ate
    re/open an existing output file, append any new data after any existing data

    ios::out | ios::noreplace
    open new file, fail if it already exists

    ios::out | ios::nocreate | ios::trunc
    open an existing file for output, fail if file doesn't exist, throw
    away existing contents and create a new file.

    ø¤º°`°º¤ø,¸¸,ø¤º°`°º¤ø,¸¸,ø¤º°`°º¤ø,¸¸,ø¤º°`°º¤ø,¸

    So in the example below, you might want to change the ‘ios::ate’ to ‘ios::out | ios::ate’ if the output file does not exist, which should not be true for the hosts file. But will be true with ‘results.txt’. So when you post “Hey you code dosn’t work!” I can say RTFM j/k

    ø¤º°`°º¤ø,¸¸,ø¤º°`°º¤ø,¸¸,ø¤º°`°º¤ø,¸¸,ø¤º°`°º¤ø,¸


    Ive included in this example a way to take input as arguments from the command line as defined in iostream.h:

    int main(int argc, char *argv[])

    the integer argc holds the number of arguments entered at the command line. The name of the program is counted amoung the arguments

    the character array argv[] holds the actual arguments as strings (more or less), the name of the program would be argv[0] therefore we’ve used argv[1] to work with the name of the site given on the command line.



    ***************************

    /*hostc.cpp*/


    /* A small program to illustrate writeing to a file.
    This can append to your host file if you change the path to
    point to it

    usage hostc [site.name] If you forget to enter a site as an arg
    the program will prompt you for it*/


    #include < iostream.h>
    #include < fstream.h>

    int main(int argc, char *argv[])
    {
    if (argc == 1)

    /* if no arguments are given, ask for input */

    {
    cout <<endl<<endl;
    cout<< "Command Line Format: hostc <sitemane>" <<endl<<endl;
    cout << "Enter a Site to be blocked : ";
    char site[50]; //50 should handle all site names
    cin >> site;
    ofstream out1;
    //out1.open("c:\\windows\\hosts.sam", ios::ate);
    //out1.open("c:\\winnt\\system32\\drivers\\etc\\hosts", ios::ate);
    out1.open("c:\\results.txt", ios::ate);
    out1 << "127.0.0.1\t" << site << endl;
    out1.close();
    cout <<endl<<endl<< site << " Has Been Blocked"<<endl<<endl;
    cout << "by TedOb1"<<endl;
    return 0; //exit program
    }

    //if command line arguments are present, continue here

    // declare an output stream
    ofstream out1;

    // specify an output location
    out1.open("c:\\results.txt", ios::ate);
    //out1.open("c:\\windows\\hosts.sam", ios::ate);
    //out1.open("c:\\winnt\\system32\\drivers\\etc\\hosts", ios::ate);

    // print to it
    out1 << "127.0.0.1\t" << argv[1]<< endl;

    //finished, close the file.
    out1.close();
    cout <<endl<<endl<< argv[1] << " Has Been Blocked"<<endl<<endl;
    cout << "by TedOb1"<<endl;
    return 0;
    }
    Bukhari:V3B48N826 “The Prophet said, ‘Isn’t the witness of a woman equal to half of that of a man?’ The women said, ‘Yes.’ He said, ‘This is because of the deficiency of a woman’s mind.’”

  2. #2
    Banned
    Join Date
    Oct 2002
    Posts
    30
    awesome C++ tutorial. Alot of us are C++ programmers anyway and this should benefit us.

  3. #3
    Senior Member
    Join Date
    Jan 2002
    Posts
    1,207
    One other note of interest to Windows (and any other system which uses backslash, such as dos) C, C++, Perl, Java etc programmers...

    The backslashes deal is inconvenient, you can avoid it easily by simply using forward slashes instead. The Windows C library treats them the same, and there's no need to escape them.

    Additionally it'll make things easier when you port your program from (or to) any other operating system, which probably uses forward slashes anyway.

  4. #4
    () \/V |\| 3 |) |3\/ |\|3G47|\/3
    Join Date
    Sep 2002
    Posts
    744
    Thanks, Tedob1 - nice tutorial.

    Regarding the subject of books, I just finished two file operations programs and found the book my class uses to be very thorough on the subject. I'm using Starting Out With C++ - Third ed. by Tony Gaddis. This book has a whole chapter on the subject of file operations. It covers everything from setting up the program for file input/output to binary files, random access files, etc. There are LOTS of code, examples, and problems in each chapter.

    For those who may be interested you can view sample pages and read an overview of the book here.


    ---------------------

    "Definitions are the guardians of rationality, the first line of defense against the chaos of mental disintegration. - Ayn Rand"

  5. #5
    Senior Member
    Join Date
    Jun 2004
    Posts
    137
    Tedob 1
    I will try this one out,
    I think that you are positive and
    No doubt about it !!!!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •