用c++打开一个文件,输出文件中的文本

Open a file with C++ and output the text that is in the file

本文关键字:文件 输出 文本 一个 c++      更新时间:2023-10-16

我试图用c++打开一个文件并输出文件中的文本。我似乎不知道我做错了什么。以下是我到目前为止写的。

#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
    char fileName[50];
    ifstream infile;

    cout << "Enter the name of the file you would like to open: ";
    cin.getline(fileName, 50);
    infile.open(fileName);

    if(!infile.is_open())
    {
        exit(EXIT_FAILURE);
    }
    char line[75];
     infile >> line;
    while (infile.good()) 
    {
        cout << line << " ";
        infile >> line;
    }

    system("pause");
    return 0;
}

在我输入文件名并按enter键后,CMD提示符就关闭了。我知道这个文件存在,但是我不知道为什么它退出了。显然,这是因为退出命令,但它应该是打开的。我做错了什么?

你不需要一行一行地读/写文件;c++已经支持一步复制文件。你也应该用string代替char[];一方面,这意味着您不需要将字符串的最大长度限制为任意长度(如果文件的路径名超过50个字符,或者文件的行超过75个字符怎么办?)

还要注意您的文件复制代码是错误的:它将从文件中删除所有空白,因为infile >> line读取一行(使用readline),而是一个单词,丢弃空白。

同样,如果不能打开文件,你的代码应该给出一个错误消息,而不是只是默默地返回(你提供一个错误返回,这是非常好的,但除非你从一个真正给你错误返回反馈的地方调用它,否则你永远不会知道它。

最后,system("pause")应该在RAII类中完成,所以它保证在返回时退出(然而,exit不会调用析构函数,所以除非你想使用atexit,否则你应该在' main ' '中使用return)。然而,一个更好的主意是不把它放在代码中,而是在程序结束后不会立即关闭的终端中运行它。

下面是实现这些建议的程序:
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
  // make sure that system("pause") is called on all exit paths
  struct cleanup
  {
    ~cleanup() { std::system("pause"); }
  } do_cleanup;
  // get the file name
  std::string filename;
  std::cout << "Enter the name of the file you would like to open: ";
  std::getline(std::cin,filename);
  if (!std::cin)
  {
    std::cerr << "Failed to read the file name.n";
    return EXIT_FAILURE;
  }
  // open the file
  std::ifstream infile(filename.c_str());
  if (!infile)
  {
    std::cerr << "Could not open file: " << filename << "n";
    return EXIT_FAILURE;
  }
  // print the file
  std::cout << infile.rdbuf();
  // close the file
  infile.close();
  if (!infile)
  {
    std::cerr << "Could not properly close file: " << filename << "n";
    return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}

没有必要使用char[]。你甚至有#includestring,所以就用它吧。

string fileName;
cout << "Enter the name of the file you would like to open: ";
cin >> fileName;
// or
// getline(cin, fileName);
ifstream infile(fileName);
if (infile.fail()) {
    exit(EXIT_FAILURE);
}
string line;
while (infile >> line) {
    cout << line << " ";
}
system("pause");
return 0;

我还修改了一些东西,使它更干净。

谢谢你的帮助。是的,文件放错文件夹了。这是一个新的疏忽!