【问题标题】:How do I print the content of a file?如何打印文件的内容?
【发布时间】:2015-04-07 18:26:08
【问题描述】:

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

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

例如,这是行不通的:

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

【问题讨论】:

  • 这是你的整个程序吗?是否有任何#include 指令?消息“error C2660”是特定于编译器的;完整的错误信息是什么?
  • 这完全是错误的。请先看看std::ifstreamfopen() 不是你在 C++ 中想要的。

标签: c++ file


【解决方案1】:

#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; }

【讨论】:

    【解决方案2】:
    1. 您不能将

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

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

    解决办法:需要把文件和可执行文件放在同一目录下

    f = fopen_s(s.c_str(), "rt");
    
    1. 您无法识别

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

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-12
      • 2016-05-14
      • 1970-01-01
      • 2016-01-10
      • 2021-03-01
      • 2021-08-02
      • 2013-03-11
      • 2013-08-19
      • 2017-08-06
      相关资源
      最近更新 更多