在 C 和 C++ 中逐行阅读?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5597513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Line by line reading in C and C++?
提问by mushroom
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.)
我想从 C 或 C++ 中的文件中逐行读取,并且当我假设某行的某些固定大小时,我知道如何执行此操作,但是是否有一种简单的方法可以以某种方式计算或获取行所需的确切大小或文件中的所有行?(逐字阅读直到换行对我也有好处,如果有人可以这样做的话。)
回答by Jeff Foster
If you use a streamed reader, all this will be hidden from you. See getline
. The example below is based from the code here.
如果您使用流式阅读器,所有这些都将对您隐藏。见getline
。下面的示例基于此处的代码。
// getline with strings
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string str;
ifstream ifs("data.txt");
getline (ifs,str);
cout << "first line of the file is " << str << ".\n";
}
回答by Jonathan Leffler
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.
在 C 中,如果您有 POSIX 2008 库(例如,更新版本的 Linux),则可以使用 POSIXgetline()
函数。如果您的库中没有该功能,您可以很容易地实现它,这可能比发明自己的界面来完成这项工作要好。
In C++, you can use std::getline()
.
在 C++ 中,您可以使用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.
尽管这两个函数具有相同的基本名称,但调用约定和语义却大不相同(因为 C 语言和 C++ 语言大不相同)——当然,它们都从文件流中读取一行数据。
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.
没有一种简单的方法可以判断文件中最长的行有多大——除非通过阅读整个文件来找出,这有点浪费。
回答by Stealth Rabbi
I would use an IFStream and use getline to read from a file.
我会使用 IFStream 并使用 getline 从文件中读取。
http://www.cplusplus.com/doc/tutorial/files/
http://www.cplusplus.com/doc/tutorial/files/
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
回答by Steve
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 fgetsto 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.
对于 c 语言编程,请尝试使用fgets读取一行代码。如果遇到换行符,它将读取 n 个字符或停止。您可以读取大小为 n 的小缓冲区,直到字符串中的最后一个字符成为换行符。
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:
以下是如何使用小缓冲区读取显示整行文件的示例:
#include <stdio.h>
#include <string.h>
int main()
{
FILE * pFile;
const int n = 5;
char mystring [n];
int lineLength = 0;
pFile = fopen ("myfile.txt" , "r");
if (pFile == NULL)
{
perror ("Error opening file");
}
else
{
do
{
fgets (mystring , n , pFile);
puts (mystring);
lineLength += strlen(mystring);
} while(mystring[strlen ( mystring)-1] != '\n' && !feof(pFile));
fclose (pFile);
}
printf("Line Length: %d\n", lineLength);
return 0;
}
回答by Marlon
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 use fgets
and keep reallocating a buffer until the last character is the '\n'
, then we know we have read the entire line.
在 C++ 中,您可以使用该std::getline
函数,它接受一个流并读取第一个'\n'
字符。在 C 中,我只会使用fgets
并继续重新分配缓冲区,直到最后一个字符是'\n'
,然后我们知道我们已经阅读了整行。
C++:
C++:
std::ifstream file("myfile.txt");
std::string line;
std::getline(file, line);
std::cout << line;
C:
C:
// I didn't test this code I just made it off the top of my head.
FILE* file = fopen("myfile.txt", "r");
size_t cap = 256;
size_t len = 0;
char* line = malloc(cap);
for (;;) {
fgets(&line[len], cap - len, file);
len = strlen(line);
if (line[len-1] != '\n' && !feof(file)) {
cap <<= 1;
line = realloc(line, cap);
} else {
break;
}
}
printf("%s", line);
回答by user411313
getline is only POSIX, here is an ANSI (NOmax-line-size info needed!):
函数getline只有POSIX,这里是一个ANSI(NO最大行大小的信息需要!):
const char* getline(FILE *f,char **r)
{
char t[100];
if( feof(f) )
return 0;
**r=0;
while( fgets(t,100,f) )
{
char *p=strchr(t,'\n');
if( p )
{
*p=0;
if( (p=strchr(t,'\r')) ) *p=0;
*r=realloc(*r,strlen(*r)+1+strlen(t));
strcat(*r,t);
return *r;
}
else
{
if( (p=strchr(t,'\r')) ) *p=0;
*r=realloc(*r,strlen(*r)+1+strlen(t));
strcat(*r,t);
}
}
return feof(f)?(**r?*r:0):*r;
}
and now it's easy and short in your main:
现在你的主要内容很容易和简短:
char *line,*buffer = malloc(100);
FILE *f=fopen("yourfile.txt","rb");
if( !f ) return;
setvbuf(f,0,_IOLBF,4096);
while( (line=getline(f,&buffer)) )
puts(line);
fclose(f);
free(buffer);
it works on windows for Windows AND Unix-textfiles, it works on Unix for Unix AND Windows-textfiles
它适用于 Windows 的 Windows 和 Unix 文本文件,它适用于 Unix 的 Unix 和 Windows 文本文件
回答by Rob?
Here is a C++ way of reading the lines, using std algorithms and iterators:
这是使用 std 算法和迭代器读取行的 C++ 方式:
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
struct getline :
public std::iterator<std::input_iterator_tag, std::string>
{
std::istream* in;
std::string line;
getline(std::istream& in) : in(&in) {
++*this;
}
getline() : in(0) {
}
getline& operator++() {
if(in && !std::getline(*in, line)) in = 0;
}
std::string operator*() const {
return line;
}
bool operator!=(const getline& rhs) const {
return !in != !rhs.in;
}
};
int main() {
std::vector<std::string> v;
std::copy(getline(std::cin), getline(), std::back_inserter(v));
}