Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c++;使用getline和file而不是ifstream读取文件_C++_File_Io_Getline - Fatal编程技术网

C++ c++;使用getline和file而不是ifstream读取文件

C++ c++;使用getline和file而不是ifstream读取文件,c++,file,io,getline,C++,File,Io,Getline,我有一个文件*对象,我想逐行读取它。然而,最常见的方法是将目录传递给ifstream,并在while循环中使用getline(ifstream,line)逐行读取 但是我没有目录。我必须使用文件*。是否有一个getline()接受文件*作为参数?或者,一般来说,C++中还有另一种方法来读取行,使用文件* < 不适用于我,因为我不在linux上 我也在想如果一个ifstream可以接受一个文件而不是一个目录,但是我不确定这一点。有人能确认吗?std::vector getfileasline(FI

我有一个
文件*
对象,我想逐行读取它。然而,最常见的方法是将目录传递给
ifstream
,并在while循环中使用
getline(ifstream,line)
逐行读取

但是我没有目录。我必须使用
文件*
。是否有一个
getline()
接受
文件*
作为参数?或者,一般来说,C++中还有另一种方法来读取行,使用<代码>文件*<代码> < 不适用于我,因为我不在linux上

我也在想如果一个ifstream可以接受一个
文件而不是一个目录,但是我不确定这一点。有人能确认吗?

std::vector getfileasline(FILE*FILE){
std::vector<std::string> getFileAsLines(FILE *file) {
  std::vector<std::string> out;
  int currentIn = fgetc(file);
  std::string currentLine;

  while(currentIn != EOF) {
    if (currentIn == '\n') {
      out.push_back(currentLine);
      currentLine = std::string();
    } else {
      currentLine += (char)currentIn;
    }

    currrentIn = fgetc(file);
  }
  out.Push_back(currentLine);
  return out;
}
std::向量输出; int currentIn=fgetc(文件); std::字符串currentLine; while(currentIn!=EOF){ 如果(currentIn=='\n'){ 向外。推回(当前线路); currentLine=std::string(); }否则{ currentLine+=(char)currentIn; } currentin=fgetc(文件); } 向外。推回(当前线路); 返回; }

我没有测试它,但是这个想法应该通过测试

在您链接的答案中还有其他各种可移植解决方案,它们有什么问题吗?您可以尝试使用boost::filesystem::ifstream作为alternative@camp0我希望能举一个例子,因为我是新手。从fgets构建getline克隆并不难。一点内存分配就完成了…在您的while条件下,它应该是
&&
而不是
@Narase,这样作为终止,而(line=getNextLine(File*File)!=NULL)应该可以正常工作吗?因为“out”最初是emptyNo,所以空字符串不是NULL,因为它不是指针。看起来你来自Java/C。我编辑了该函数,使其以行列表的形式返回整个文件