【发布时间】:2021-05-04 10:28:27
【问题描述】:
我正在阅读位于 /home/documents/abc.cpp 下的 abc.cpp 文件。要打开文件,我正在执行文件操作 open("t.open("/home/documents/abc.cpp")。我可以在其中对文件执行打开操作。
我想尝试使用命令行参数读取文件名。所以我在这里尝试的是在命令行中
./a.out abc.cpp ,传递 argv[1] 作为文件名并连接字符串路径 + argv[1],当我编译代码时,我会抛出编译错误,如何要解决这个问题,请帮忙。
#include <iostream>
#include <fstream>
#include <sstream>
#include<string.h>
#include <ext/stdio_filebuf.h>
using namespace std;
int main(int argc, char *argv[])
{
ifstream t;
string path = "/home/documents/";
string file = path + argv[1];
t.open(file);
//t.open("/home/documents/abc.cpp");
string buffer;
string line;
while(t)
{
getline(t, line);
// ... Append line to buffer and go on
buffer += line;
buffer += "\n";
}
t.close();
return 0;
}
编译错误
g++ cmdLine.cpp
cmdLine.cpp: In function ‘int main(int, char**)’:
cmdLine.cpp:13:32: error: no matching function for call to ‘std::basic_ifstream<char>::open(std::string&)’
t.open(file);
^
cmdLine.cpp:13:32: note: candidate is:
In file included from cmdLine.cpp:2:0:
/usr/include/c++/4.8.2/fstream:538:7: note: void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std::ios_base::openmode = std::_Ios_Openmode]
open(const char* __s, ios_base::openmode __mode = ios_base::in)
^
/usr/include/c++/4.8.2/fstream:538:7: note: no known conversion for argument 1 from ‘std::string {aka std::basic_string<char>}’ to ‘const char*’
【问题讨论】:
-
能否分享一下编译错误?
标签: c++ file dynamic command-line-arguments