// file size

Feb 25, 2010 at 5:03am
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 Feb 25, 2010 at 4:17pm
Feb 25, 2010 at 5:48am
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.
Feb 25, 2010 at 5:56am
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;
}
Feb 25, 2010 at 4:19pm
Thank you zhugh, I appreciate your correction. I'm learning from my mistakes:-)
Feb 25, 2010 at 4:23pm
zhugh I checked example.txt and nothing there but the two lines of text entered when myfile.cpp
created example.txt.

Last edited on Feb 25, 2010 at 4:24pm
Feb 25, 2010 at 4:26pm
Thanks blackcoder41 I'll check it out and report.
Feb 25, 2010 at 9:58pm
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???
Feb 25, 2010 at 9:59pm
Thanks to all for your input :-)
Topic archived. No new replies allowed.