// file size

Compiled the following code to obtain the file size for: example.txt, and
the file size was not returned when ./myfile was executed. ./myfile returned the prompt $.

myfile.cpp was compiled using the following commands:

$ g++ -c myfile.cpp created >> myfile.o
$ g++ myfile.o -o myfile created >> executable
$ ./myfile created >> example.txt

// obtaining file size
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <fstream>
using namespace std;

int main() {
	long begin, end;
	ifstream myfile ("example.txt");
	begin = myfile.tellg();
	myfile.seekg (0, ios::end);
	end = myfile.tellg();
	myfile.close();
	cout << "size is:  " << (end-begin) << "bytes.\n";
	return 0;
}
Size is: 40 bytes
Last edited on
Code tags please, even for short code. And, to state the obvious, did you look in example.txt to see if the size was actually appended? You're redirecting the output to append to that file.
that works for me.. you could try to check if the file is really open or not

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int main() {
    long begin, end;
    ifstream myfile ("example.txt");

    if(!myfile.is_open()) {
        cout << "Error! Opening file.. :(\n";
        return EXIT_FAILURE;
    }

    begin = myfile.tellg();
    myfile.seekg (0, ios::end);
    end = myfile.tellg();
    myfile.close();
    cout << "size is: " << (end-begin) << " bytes.\n";
    return 0;
}
Thank you zhugh, I appreciate your correction. I'm learning from my mistakes:-)
zhugh I checked example.txt and nothing there but the two lines of text entered when myfile.cpp
created example.txt.

Last edited on
Thanks blackcoder41 I'll check it out and report.
blackcoder41 the file does open. I recompiled and now the program returns "size is: 38 bytes."
Honestly I don't have a clue what happened to make it work. I did not change or correct the code in any manner???
Thanks to all for your input :-)
Topic archived. No new replies allowed.