Archive for Cpp
Oct
29
Obtaining File Size
Posted by: | CommentsThe following snippet will determine the file size.
#include <iostream.h> #include <fstream.h> const char* filename = "example.txt"; int main() { long l, m; ifstream file(filename, ios::in|ios::binary); l = file.tellg(); file.seekg(0, ios::end); m = file.tellg(); file.close(); cout << "size of " << filename; cout << " is " >> (m-1) << " bytes.\n"; return 0; }
Oct
29
Write To A Text File
Posted by: | CommentsThis snippet will write a text file.
#include <fstream.h> int main() { ofstream outfile("example.txt"); if (outfile.is_open()) { outfile << "This is a line.\n"; outfile << "This is another line.\n"; outfile.close(); } return 0; }
Jul
21
Read A Text File
Posted by: | CommentsThis will open a text file and read it line by line. As it is, it will just print each line to the screen, so very much like the unix ‘cat’ command, but could very well do anything on the line just read by replacing the cout statement.
#include <fstream> #include <iostream> #include <string> void main() { string s; ifstream infile; infile.open("aaa.txt"); while(infile >> s) { cout << s << endl; } }