I want to read line by line from a file in C or C++, and I know how to do that when I assume some fixed size of a line, but is there a simple way to somehow calculate or get the exact size needed for a line or all lines in file? (Reading word by word until newline is also good for me if anyone can do it that way.)
相关问题
- Sorting 3 numbers without branching [closed]
- Multiple sockets for clients to connect to
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
getline is only POSIX, here is an ANSI (NO max-line-size info needed!):
and now it's easy and short in your main:
it works on windows for Windows AND Unix-textfiles, it works on Unix for Unix AND Windows-textfiles
In C, if you have POSIX 2008 libraries (more recent versions of Linux, for example), you can use the POSIX
getline()
function. If you don't have the function in your libraries, you can implement it easily enough, which is probably better than inventing your own interface to do the job.In C++, you can use
std::getline()
.Even though the two functions have the same basic name, the calling conventions and semantics are quite different (because the languages C and C++ are quite different) - except that they both read a line of data from a file stream, of course.
There isn't an easy way to tell how big the longest line in a file is - except by reading the whole file to find out, which is kind of wasteful.
In C++ you can use the
std::getline
function, which takes a stream and reads up to the first'\n'
character. In C, I would just usefgets
and keep reallocating a buffer until the last character is the'\n'
, then we know we have read the entire line.C++:
C:
You can't get the length of line until after you read it in. You can, however, read into a buffer repeatedly until you reach the end of line.
For programming in c, try using fgets to read in a line of code. It will read n characters or stop if it encounters a newline. You can read in a small buffer of size n until the last character in the string is the newline.
See the link above for more information.
Here is an example on how to read an display a full line of file using a small buffer:
I would use an IFStream and use getline to read from a file.
http://www.cplusplus.com/doc/tutorial/files/
If you use a streamed reader, all this will be hidden from you. See
getline
. The example below is based from the code here.