simple fileIO

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;

}




Answer this question

simple fileIO

  • ctorob

    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";

  • Devast8or

    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

  • BISDamonL

    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...



  • simple fileIO