C++ File Operations

// file_write.cpp
// Author: A.G.Raja
// Website: agraja.wordpress.com
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile (“example.txt”);
if (myfile.is_open())
{
myfile << “This is a line.\n”;
myfile << “This is another line.\n”;
myfile.close();
}
else cout << “Unable to open file”;
return 0;
}
// g++ file_write.cpp
// file_read.cpp
// Author: A.G.Raja
// Website: agraja.wordpress.com
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile (“example.txt”);
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << “Unable to open file”<<endl;
return 0;
}
//g++ file_read.cpp
Download here.
cpp_file_operations.doc
Advertisements

C File Operations

////////   file_operations.c  ////////
 #include <stdio.h>
 int main(void)
 {
 char temp[100];
 FILE *write_to_file = fopen("file.txt","w");
 fprintf(write_to_file,"%08x",0xC12E3A4);
 fclose(write_to_file);
 FILE *read_from_file = fopen("file.txt", "rb");
 fscanf(read_from_file,"%s",temp);
 printf("String read from file=%sn",temp);
 fclose(read_from_file);
 return 0;
 }

[raja@AGRAJA ~]$ gcc -Wall file_operations.c
[raja@AGRAJA ~]$ ./a.out

String read from file=0c12e3a4

Download here:

c_file_operations.doc