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