从函数 C++ 返回文件 ID

return a file id from a function c++

本文关键字:文件 ID 返回 C++ 函数      更新时间:2023-10-16

我想从函数返回一个文件 ID。我的函数应该是什么类型?

这是一个测试"main",其执行与所需功能非常相似。

    // this c++ code tests statements
//    #include </home/steve/cpincludes>
#include <iostream>     // std::cout
#include <fstream>      // std::ifstream 
#include <string>
using namespace std;
int main(){                   //   replace this line with type getid(){
const char* cname ="test.txt";
string line;
std::string name=cname;
std::ifstream is;
cout << cname <<"   "<< name <<'n';
is.open(name.c_str(),ios::in | std::ifstream::binary);
while ( getline (is,line) ) { //test read
  cout << line << 'n';    }
return (0);}                  //   replace this line with return (is) ;}

从 C++11 开始,您可以移动具体的 iostream:

std::ifstream foo(std::string const& path)
{
  std::ifstream stream{path};
  // Do whatever      
  return stream;
}

这将适用于libc++或VS> 2010,但不适用于libstdc++(直到与gcc 5.0捆绑在一起的libstdc++的下一个版本发布)。

如果您的库不支持移动流,则必须使用指针

std::unique_ptr<std::ifstream> foo(std::string const& path)
{
  auto stream = std::make_unique<std::ifstream>(path);
  // Do whatever      
  return stream;
}

或将流作为引用传递

void foo(std::ifstream& stream)
{
  // Do whatever      
}

我在思考这个问题。此代码位于用户界面函数中,但我只在那里打开文件以检查是否存在。简单的答案是

ifstream my_file("test.txt");
if (my_file) cout << "file exists";
else cout << "file not found";

(当然是适当的重组)然后我将文件名返回到 main。在 main 中打开和读取文件是一个更好的答案,因为它将其从用户界面中取出,无论如何都不属于它。它还使文件数据字符串可用于传递给其他处理函数,这是目标。