用c++打开一个文件,输出文件中的文本
Open a file with C++ and output the text that is in the file
我试图用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[]
。你甚至有#include
和string
,所以就用它吧。
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;
我还修改了一些东西,使它更干净。
谢谢你的帮助。是的,文件放错文件夹了。这是一个新的疏忽!
相关文章:
- 如何在 的开头<x>和结尾<y>之间更改带有文件输出的字符串的值
- C++对象数组的文件输出
- bcdedit 文件输出不起作用,但其他命令可以
- 如何从文本文件输出数据?(学生成绩单计划)
- 使用 C++文件 I/O 输出 pdf 文件
- C 文件输出垃圾
- 从堆栈中读取字符后,如何修复不正确的文件输出
- C++:具有随机名称的文件输出
- 在命令提示符下看到换行符,但在文件输出中可以看到 相同的字符串
- 生成文件不会生成预期的文件输出
- C++11 fgetc 在"r+b"模式下使用时向我的文件输出 0
- 使用函数从文件输出
- GCC.obj文件输出不具有确定性(.debug_info,PROGPITS部分)
- C cstdiofile :: Writestring给出了不正确的文件输出
- C 输出:STD :: COUT和文件输出没有相同的内容
- GCC和MSVC之间的文件输出不一致
- C++文件输出奇怪的数字,并且部分代码没有运行
- 如何将特定字符从TXT文件输出到特定点
- C 调用从TXT文件输出信息的函数
- 将交易从文本文件输出到屏幕