Redirecting a standard output to a file C program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows Xp Pro with SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info:

To do: Redirecting the standard output to a text file C program example

To show: How to redirect the standard output to a file using C file I/O functions

 

 

// Redirecting a standard stream

#include <stdio.h>

 

enum {SUCCESS, FAIL, STR_NUM = 6};

 

// function prototypes

void StrPrint(char **str);

int ErrorMsg(char *str);

 

int main(void)

{

// declare and define a pointer to string...

char *str[STR_NUM] = {

"Redirecting a standard stream to the text file.",

"These 5 lines of text will be redirected",

"so many things you can do if you understand the",

"concept, fundamental idea - try this one!",

"--------------DONE--------------------------"};

char filename[] = "c:\\Temp\\testnine.txt";

int reval = SUCCESS;

 

StrPrint(str);

// create file if not exist and open for writing, if exist, discard the previous content...

if(freopen(filename, "w", stdout) == NULL)

{

reval = ErrorMsg(filename);

}

else

{

// call StrPrint() function...

StrPrint(str);

// close the standard output...

fclose(stdout);

}

return reval;

}

 

// StrPrint() function definition

void StrPrint(char **str)

{

int i;

 

for(i=0; i<STR_NUM; i++)

// to standard output-screen/console...

printf("%s\n", str[i]);

}

 

// ErrorMsg() function definition

int ErrorMsg(char *str)

{

printf("Problem, cannot open %s.\n", str);

return FAIL;

}

 

Output example:

 

Redirecting a standard stream to the text file.

These 5 lines of text will be redirected

so many things you can do if you understand the

concept, fundamental idea - try this one!

--------------DONE--------------------------

(null)

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index