从函数 C++ 返回文件 ID
return a file id from a function c++
我想从函数返回一个文件 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 中打开和读取文件是一个更好的答案,因为它将其从用户界面中取出,无论如何都不属于它。它还使文件数据字符串可用于传递给其他处理函数,这是目标。
相关文章:
- 从函数角度看ID到文件路径的内部与外部映射
- FFMPEG配置文件级别id大小无效
- 如何将 id 写入文件,然后将其读回?
- 为什么错误"permission denied","id returned 1 exit status"仅在 IM 使用 C++ 中的头文件 fstream 时才出现
- C :数据文件有错误:预期的无限制ID
- C 和 C++:带有错误"Expected unqualified-id"的数据文件
- 有没有办法使用从 GetFileInformationByHandle() 获取的文件 id(FILE_ID_DESCR
- 从.txt文件找到并验证C 的特定用户ID
- 读取图形可视化的点文件,而无需在提升图中存储节点 ID
- 通过我的可执行文件的资源 ID 获取图标索引,C++
- 在头文件的数组中定义资源 ID
- (C++)错误:在数字常量之前应为非限定id--从文件读取时
- PIN - 获取正在检测的二进制文件的进程 ID
- 从函数 C++ 返回文件 ID
- Apple Mach-O 链接器 (Id) 错误 1 - 带有头文件的基本C++
- 来自 Qt 文件的编译时错误:令牌之前的预期非限定 id ')'
- 在文本文件中找到10个最大的数量行,其中包含发货ID, UPC代码,数量
- 如何从std::ofstream获取文件id
- 如何使用文件的ID在一组目录中查找文件
- 尝试在 Cygwin 中构建 boost 文件系统时出错: 错误:在"&&"令牌之前预期为非限定 ID