如何打印出文件的内容?C++ 文件流
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35201919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I print out the contents of a file? C++ File Stream
提问by Lucas Farleigh
I am using fstream and C++ and all I want my program to do is to print out to the terminal the contents of my .txt file. It may be simple, but I have looked at many things on the web and I can't find anything that will help me. How can I do this? Here is the code I have so far:
我正在使用 fstream 和 C++,我希望我的程序做的就是将我的 .txt 文件的内容打印到终端。这可能很简单,但我在网上看了很多东西,找不到任何对我有帮助的东西。我怎样才能做到这一点?这是我到目前为止的代码:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
string output;
ifstream myfile;
ofstream myfile2;
string STRING;
myfile.open ("/Volumes/LFARLEIGH/Lucas.txt");
myfile2 << "Lucas, It Worked";
myfile >> STRING;
cout << STRING << endl;
myfile.close();
return 0;
}
Thank you in advance. Please forgive me if this is very simple as I quite new to C++
先感谢您。如果这很简单,请原谅我,因为我对 C++ 很陌生
回答by Sam Varshavchik
There's no reason to reinvent the wheel here, when this functionality is already implemented in the standard C++ library.
当此功能已在标准 C++ 库中实现时,没有理由在这里重新发明轮子。
#include <iostream>
#include <fstream>
int main()
{
std::ifstream f("file.txt");
if (f.is_open())
std::cout << f.rdbuf();
}
回答by Muhammad bakr
#include <iostream>
#include <fstream>
int main()
{
string name ;
std::ifstream dataFile("file.txt");
while (!dataFile.fail() && !dataFile.eof() )
{
dataFile >> name ;
cout << name << endl;
}
回答by Velu Vijay
Try this, just modified at some places. You had tried to open a file using extracter (i.e, ifstream) but overwriting this file using inserter (i.e, ofstream) without opening the file, that ifstreamand ofstreamwere two different classes. so, they don't understand.
试试这个,只是修改了一些地方。您曾尝试使用提取器(即,ifstream)打开文件,但使用插入器(即,ofstream)覆盖该文件而不打开文件,即ifstream和ofstream是两个不同的类。所以,他们不明白。
#include<iostream>
#include<fstream>
using namespace std;
int main(){
string output;
ifstream myfile;
ofstream myfile2;
string STRING;
// output stream || inserting
myfile2.open ("/Volumes/LFARLEIGH/Lucas.txt");
myfile2 << "Lucas, It Worked";
myfile2.close();
// input stream || extracting
myfile.open("/Volumes/LFARLEIGH/Lucas.txt");
myfile >> STRING;
cout << STRING << endl;
myfile.close();
return 0;
}