none
simple fileIO RRS feed

  • Question

  • Hello,

    1) can anyone please tell me how to output things to files rather than the screen in c++ ? preferrably using 'cout'? Code snippets would be great!

    2) Can anyone please tell me no file is created in the directory c:\Ido\proggen  after executing the following code:



    // win32app.cpp : Defines the entry point for the console application.

    //

    #include "stdafx.h"

     

     

    int _tmain(int argc, _TCHAR* argv[])

    {

    const char * filename = "c:\Ido\proggen\ido.out";

    FILE *file;

    file = fopen( filename, "w");

    putc(555,file);

    fclose(file);

    //fopen ido;

    return 0;

    }

    Friday, October 7, 2005 4:03 PM

Answers

All replies

  • 1) cout is for writing to the console - you should not, in general, use it to write to a file. Note: you can re-direct the output of your program to a file.

    MyApp > MyFile.txt

    If you want to use cout-like syntax then you should take a look at ofstream and the associated iterators.

    2) I suspect the problem here is the '\' character as this is the 'escape' character it needs to be escaped when used in a string. For example:

    const char* filename = "C:\\Ido\\proggen\\ido.out";
    Friday, October 7, 2005 4:11 PM
    Moderator
  • Thanks! That helped!

    However, how can I add complete strings to the file. i.e. instead of the normal ' printf("hello there") to the screen I'd like to print these lines into a txt file...

    Friday, October 7, 2005 4:21 PM
  • There are many ways to do this - you can use Win32 functions, C functions, or C++ functions. You stated above that you wanted to use cout like syntax so you should take a look at ofstream and its associated iterators.

    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vcstdlib/html/vclrf_fstream_ofstream.asp
    Friday, October 7, 2005 4:24 PM
    Moderator