Get the contents of a file, character by character

  • Thread starter Thread starter Cinimod
  • Start date Start date
  • Tags Tags
    File
Click For Summary

Discussion Overview

The discussion revolves around reading the contents of a file character by character in C and C++. Participants are exploring methods to open a file, handle whitespace, and store characters in an array while printing them to the screen. The conversation includes both technical explanations and suggestions for code implementation.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Mathematical reasoning

Main Points Raised

  • One participant expresses difficulty in reading a file character by character and mentions that their current implementation stops at the first whitespace.
  • Another participant requests to see the code that has been written so far.
  • A participant suggests using an EOF function to determine when the end of the file has been reached, proposing a while loop structure for reading characters.
  • Another suggestion is made to use the getline() function for reading the file instead of streaming it directly.
  • A later reply clarifies that using the extraction operator (>>) skips whitespace and recommends using the istream get() function to read characters without skipping any.
  • One participant critiques the common misconception about the eof() function, explaining that it only returns true after an attempt to read past the end of the file has failed, and provides an alternative method for reading lines correctly.
  • Another participant thanks the group for their input and suggestions.

Areas of Agreement / Disagreement

There is no consensus on the best approach to read a file character by character, as participants propose different methods and clarify misconceptions about file reading functions.

Contextual Notes

Participants discuss various methods for file reading, highlighting limitations and potential pitfalls associated with using eof() and the extraction operator. The conversation reflects differing opinions on the best practices for handling file input in C and C++.

Who May Find This Useful

Programmers and students working on file input/output operations in C and C++, particularly those interested in character-level file manipulation and common pitfalls in file handling.

Cinimod
Messages
34
Reaction score
0
I am stuck on a program where I need to open a file, and print out the contents to a screen, but at the same time, I want to save each character in the file (spaces included) to an element of an array. However, I am having a problem opening the file and going through it character by character (I don't know if there are any functions already available to help me with this). What I have at the moment prints off the file to screen, but stops at the first whitespace it encounters. I ideally want to be able to do it in both C and C++, but at the moment, I am having trouble just doing it in the one language.
 
Technology news on Phys.org
Can you post what you have so far?
 
o right. sorry.
Code:
int main(int argc, char *argv[])
{
int i;
char string[*argv[3]],c;

if(argc < 3) {
usage(argv[0]);
exit(1);
}

ifstream b_file(argv[2]);

b_file >> c;
cout << c;

cin.get();
}

void usage(char *cmd)
{
printf("Usage: %s <file to read with complete path> <Number of characters to scan>\n", cmd);
}
I have to admit, there isn't much of a program at the moment, but I've only just started. I know that to read it character by character, I will need to implement a for loop (hence why I declared i, since I plan to use it as an index).
 
It's been a long while since I programmed C(++) but I think there should be an EOF (end of file) function that tells you when you have reached the end of the file.
So probably the lines
Code:
b_file >> c;
cout << c;
would change into something like
Code:
while(!b_file.eof()) {
b_file >> c;
cout << c;
}

but for the exact syntax you should look at the documentation a bit.
 
Also, you might want to use getline() instead of just streaming in the file.
Check out the examples on file I/O with fstreams http://www.cplusplus.com/doc/tutorial/files.html
 
Cinimod said:
o right. sorry.
Code:
b_file >> c;

This skips whitespace (blanks, tabs, newlines). To read a file one character at a time, without skipping anything, use the istream get() member function:

Code:
while (b_file.get(c))   // the loop terminates when you try to read past end of file
{
    // do what you need to do with c here
}
 
CompuChip said:
Check out the examples on file I/O with fstreams http://www.cplusplus.com/doc/tutorial/files.html

Unfortunately, that page perpetuates a very common misconception about the eof() member function:

Notice how we have used a new member function, called eof() that returns true in the case that the end of the file has been reached. We have created a while loop that finishes when indeed myfile.eof() becomes true (i.e., the end of the file has been reached).

and illustrates it with the following code:

Code:
while (! myfile.eof() )
{
    getline (myfile,line);
    cout << line << endl;
}

The eof() member function actually signals "true" only after you have tried to read past the end of file and failed. In the example above, when getline() reads the last line, eof() remains "false" because getline() does not try to read past the newline that terminates the last line. Therefore the loop goes around one more time, getline() tries to read past the end of file, fails, and possibly puts garbage into "line". The output statement then processes that extra garbage line before the loop cycles back to the top and only then does eof() terminate the loop.

The correct way to do this is as follows:

Code:
while (getline (myfile,line))
{
    cout << line << endl;
}

This works because in a Boolean context, getline() evaluates as "true" or "false" depending on whether the input succeeded or failed. Other standard C++ input operations behave the same way. Notice how I used get() in my preceding post. Similarly, if you want to read one "word" at a time, skipping whitespace, you can do this:

Code:
string word;
while (myfile >> word)
{
    cout << word << endl;
}
 
Thank you very much guys.
 

Similar threads

  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 9 ·
Replies
9
Views
2K
Replies
7
Views
3K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 33 ·
2
Replies
33
Views
3K
  • · Replies 9 ·
Replies
9
Views
4K
  • · Replies 29 ·
Replies
29
Views
4K
  • · Replies 2 ·
Replies
2
Views
2K
Replies
81
Views
8K