fbpx

Job Interview question: How to stream output, open file, and read file in C++ and C

(Last Updated On: May 19, 2010)

Job Interview question: How to stream output, open file, and read file in C++ and C

To stream to clog, set:
#include
#include

void main ( )
{
using namespace std;

// open the file “file_name.txt”
// for reading
ifstream in(“file_name.txt”);

// output the all file to stdout
if ( in )
cout << in.rdbuf(); else // if the ifstream object is in a bad state // output an error message to stderr clog << "Error while opening the file" << endl; } How to open and read a file: #include

void readone();

int main(int argn, char **argv)
{
int i;
for (i=0; i<=2; i++){ readone(); } } void readone() { static int ctr = 0; FILE *f = fopen("test.txt", "r"); char str[100]; int i; for (i=0; i<=ctr; i++){ fscanf(f, "%[^\n]\n", str); } puts(str); fclose(f); ctr++; } Beaware of ftell and fseek: /* ftell example : getting size of a file */ #include

int main ()
{
FILE * pFile;
long size;

pFile = fopen (“myfile.txt”,”rb”);
if (pFile==NULL) perror (“Error opening file”);
else
{
fseek (pFile, 0, SEEK_END);
size=ftell (pFile);
fclose (pFile);
printf (“Size of myfile.txt: %ld bytes.\n”,size);
}
return 0;
}

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

Subscribe For Latest Updates

Sign up to best of business news, informed analysis and opinions on what matters to you.
Invalid email address
We promise not to spam you. You can unsubscribe at any time.

NOTE!

Check NEW site on stock forex and ETF analysis and automation

Scroll to Top