views:

72

answers:

2

Below is my code. My problem is, my destination file always has a lot more strings than the originating file. Then, inside the for loop, instead of using i < sizeof more, I realized that I should use i < sizeof file2 . Now my problem is, how to get the size of file2?

int i = 0;

FILE *file2 = fopen(LOG_FILE_NAME,"r");
wfstream file3 (myfile, ios_base::out);


// char more[1024];
char more[SIZE-OF-file2];


for(i = 0; i < SIZE-OF-file2 ; i++)
{       
    fgets(more, SIZE-OF-file2, file2);
    file3 << more;
}

fclose(file2);
file3.close();
+1  A: 

You can do this using GetFileSize(). By reading the size of the file from the filesystem, you will avoid a lot of unnecessary computation. This can also be done with _stat(), or on unix it would just be stat().

Here is the definition:

DWORD WINAPI GetFileSize( __in HANDLE hFile, __out_opt LPDWORD lpFileSizeHigh );

Doc for GetFileSize:

http://msdn.microsoft.com/en-us/library/aa364955%28VS.85%29.aspx

Alternatively you might want to use _stat()

Doc for stat: http://msdn.microsoft.com/en-us/library/14h5k7ff%28VS.80%29.aspx

Tom Dignan
+2  A: 

The most basic way is to fseek to the end of the file and to use ftell to give you the offset. The other (stat) functions also do this, but they're not cross-platform. Of course, if you want your code rot in hell, you could also use GetFileSize().

fseek(file, 0, SEEK_END);
off_t offset = ftell(file);
fseek(file, 0, SEEK_SET);

Every time you refer to C as Visual C, or C++ as Visual C++ I die a little.

Aviral Dasgupta
OP wasn't referring to C as Visual C, C++, or visual C++. S/he was actually talking about Visual C++ if you read the question at all. I love C89/C99 just as much as the next guy does, and generally hate windows. Although the most effective way to solve the problem for "Visual C++" is to use the API they provide you with.As far as "code rotting in hell" goes, try using the preprocessor. That's why it exists.
Tom Dignan
... which is basically C with Microsoft specific extensions...
Aviral Dasgupta
... what the preprocessor ? :)
Romain Hippeau
The preprocessor is what replaces macros/includes files etc. #include, #define, #ifdef #endif #if, etc are preprocessor directives. You could use it to conditionally call a function based on what platform you're compiling for. i.e. #ifdef WIN32 ... GetFileSize() #endif
Tom Dignan
@Tom I'll repeat what Romain's said, in a different context though -- "What The Preprocessor!" Why would you want to use something else when you already have a solution that works everywhere?
Aviral Dasgupta
I can't speak for whether OP is reading a large file, but try your method on a 16GB file, then after your nap, tell me why you might want to use my solution of reading the size from the filesystem nodes where it is already stored.
Tom Dignan
@Tom The limit is actually 2 GB, but yeah... there are some drawbacks...
Aviral Dasgupta