如何打印文件内容?

时间:2015-04-07 18:26:09

标签: c++ file

如何打印文件的内容,其名称是通过我的程序命令行指定的?

我不知道如何通过命令行提供文件名以及如何使用它。

对于ex,这不起作用:

int main(int argc, char *argv[])
{
    FILE *f;
    char s[20];
    cin >> s;
    f=fopen_s(s,"rt");
    std::cout << f;
    _getch();
    return 0;
}

错误C2660

2 个答案:

答案 0 :(得分:0)

#include <iostream> #include <fstream> int main(int argc , char *argv[]) { if(argc < 2) { std::cout << " Wrong usage " << std::endl; exit(0); } std::string file_name = argv[1]; std::ifstream fs; fs.open(file_name.c_str()); std::cout << file_name << std::endl; std::string line ; while(fs >> line) { std::cout << line << std::endl; } return 0; }

答案 1 :(得分:0)

  1. 您不能将<<运算符与char []
  2. 一起使用

解决方案:您可以使用std :: string

std::string s;
  1. 使用字符串的c_str()值作为fopen_s(name,“ rt”)中的名称

解决方案:您需要将文件与可执行文件放在同一目录中

f = fopen_s(s.c_str(), "rt");
  1. 您无法引用<< FILE * f

解决方案:在打印每一行时逐行读取文件内容

char* line; //used to receive data for each line
int length; //used to represent how many characters have received
while ((getline(&line, &length, f) != -1) {
    print("%s", line);
}
相关问题