Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C++ (http://www.programmingforums.org/forum15.html)
-   -   file reading anomaly (http://www.programmingforums.org/showthread.php?t=12542)

Lesliect6 Feb 9th, 2007 12:51 PM

file reading anomaly
 
Hello,

I would like to know the cause of this anomaly in a recent code I made. The code opens a file, and reads the number of lines in it. It works with some files, and does not with others. The code snippet is the following :

:

...
#define NEXT_LINE 10
...
int main()
{
...
char c, str[256];
int lines=1;

ifstream fin;
cin >> str;
fin.open(str);

while (fin.good())
{
    c=fin.get();
    if (c==NEXT_LINE) lines++;
}

cout << "The number of lines in the file : " << lines;
...


While this code works with a .txt and a .bak file I made for the program, it does not work with an .x and an .exe file. I don't know where I made the error, could you help me?

Thank you,
Leslie

DaWei Feb 9th, 2007 1:50 PM

.exe files and .x files are binary files. They are not organized into text lines with a newline character. As a matter of fact, they are not organized into lines, at all. Any binary value of 10 which happens to be part of the data will give you a "line" count.

Confine your line counting to files which have lines and count bytes (total length) for the others. For total length, check out 'stat' and friends. You don't even have to open the file. For line counts, why don't you just read lines (let the library function look for newlines) and be done with it.

Lesliect6 Feb 9th, 2007 1:59 PM

Wow thank you DaWei, you solved it. It was so obvious though...binary files:)


All times are GMT -5. The time now is 1:54 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC