如何在 C++ 中读取和写入文本文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6051865/
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 to read and write to a text file in C++?
提问by Nate
Hey everyone, I have just started to learn C++ and I wanted to know how to read and write to a text file. I have seen many examples but they have all been hard to understand/follow and they have all varied. I was hoping that someone here could help. I am a total beginner so I need clear instructions. Here is an example of what i'm trying to do:
大家好,我刚刚开始学习 C++,我想知道如何读取和写入文本文件。我看过很多例子,但它们都很难理解/遵循,而且它们各不相同。我希望这里有人可以提供帮助。我是一个完全的初学者,所以我需要明确的指示。这是我正在尝试做的一个例子:
#include <iostream>
#include <fstream>
using namespace std;
string usreq, usr, yn, usrenter;
int start ()
{
cout << "Welcome..."
int main ()
{
cout << "Is this your first time using TEST" << endl;
cin >> yn;
if (yn == "y")
{
ofstream iusrfile;
ofstream ousrfile;
iusrfile.open("usrfile.txt", "w");
iusrfile >> usr;
cout << iusrfile;
iusrfile.close();
cout << "Please type your Username. \n";
cin >> usrenter;
if (usrenter == usr)
{
start ();
}
}
else
{
cout << "THAT IS NOT A REGISTERED USERNAME.";
}
return 0;
}
回答by Code_So1dier
Header files needed:
需要的头文件:
#include <iostream>
#include <fstream>
declare input file stream:
声明输入文件流:
ifstream in("in.txt");
declare output file stream:
声明输出文件流:
ofstream out("out.txt");
if you want to use variable for a file name, instead of hardcoding it, use this:
如果要使用变量作为文件名,而不是对其进行硬编码,请使用以下命令:
string file_name = "my_file.txt";
ifstream in2(file_name.c_str());
reading from file into variables (assume file has 2 int variables in):
从文件读取到变量(假设文件中有 2 个 int 变量):
int num1,num2;
in >> num1 >> num2;
or, reading a line a time from file:
或者,从文件中一次读取一行:
string line;
while(getline(in,line)){
//do something with the line
}
write variables back to the file:
将变量写回文件:
out << num1 << num2;
close the files:
关闭文件:
in.close();
out.close();
回答by daalbert
Look at this tutorialor this one, they are both pretty simple. If you are interested in an alternative this is how you do file I/O in C.
看看 本教程或这一个,他们都非常简单。如果您对替代方案感兴趣,这就是您在 C 中执行文件 I/O 的方式。
Some things to keep in mind, use single quotes '
when dealing with single characters, and double "
for strings. Also it is a bad habit to use global variableswhen not necessary.
要记住的一些事情,'
处理单个字符时使用单引号"
,字符串使用双引号。在不必要的时候使用全局变量也是一个坏习惯。
Have fun!
玩得开心!
回答by Nekuromento
Default c++ mechanism for file IO is called streams.
Streams can be of three flavors: input, output and inputoutput.
Input streams act like sources of data. To read data from an input stream you use >>
operator:
文件 IO 的默认 c++ 机制称为流。流可以具有三种风格:输入、输出和输入输出。输入流就像数据源一样。要从输入流中读取数据,请使用>>
运算符:
istream >> my_variable; //This code will read a value from stream into your variable.
Operator >>
acts different for different types. If in the example above my_variable
was an int, then a number will be read from the strem, if my_variable
was a string, then a word would be read, etc.
You can read more then one value from the stream by writing istream >> a >> b >> c;
where a, b and c would be your variables.
运算符>>
对不同类型的行为不同。如果在上面的示例中my_variable
是一个 int,那么将从 strem 中读取一个数字,如果my_variable
是一个字符串,则将读取一个单词,等等。您可以通过写入istream >> a >> b >> c;
where a、b 和c 将是你的变量。
Output streams act like sink to which you can write your data. To write your data to a stream, use <<
operator.
输出流就像接收器,您可以将数据写入其中。要将数据写入流,请使用<<
运算符。
ostream << my_variable; //This code will write a value from your variable into stream.
As with input streams, you can write several values to the stream by writing something like this:
与输入流一样,您可以通过编写以下内容将多个值写入流:
ostream << a << b << c;
Obviously inputoutput streams can act as both.
显然输入输出流可以同时充当两者。
In your code sample you use cout
and cin
stream objects.
cout
stands for console-output and cin for console-input
. Those are predefined streams for interacting with default console.
在您的代码示例中,您使用cout
和cin
流对象。
cout
代表控制台输出,cin 代表console-input
. 这些是用于与默认控制台交互的预定义流。
To interact with files, you need to use ifstream
and ofstream
types.
Similar to cin
and cout
, ifstream
stands for input-file-stream
and ofstream
stands for output-file-stream
.
要与文件交互,您需要使用ifstream
和ofstream
类型。与cin
and类似cout
,ifstream
代表input-file-stream
和ofstream
代表output-file-stream
。
Your code might look like this:
您的代码可能如下所示:
#include <iostream>
#include <fstream>
using namespace std;
int start()
{
cout << "Welcome...";
// do fancy stuff
return 0;
}
int main ()
{
string usreq, usr, yn, usrenter;
cout << "Is this your first time using TEST" << endl;
cin >> yn;
if (yn == "y")
{
ifstream iusrfile;
ofstream ousrfile;
iusrfile.open("usrfile.txt");
iusrfile >> usr;
cout << iusrfile; // I'm not sure what are you trying to do here, perhaps print iusrfile contents?
iusrfile.close();
cout << "Please type your Username. \n";
cin >> usrenter;
if (usrenter == usr)
{
start ();
}
}
else
{
cout << "THAT IS NOT A REGISTERED USERNAME.";
}
return 0;
}
For further reading you might want to look at c++ I/O reference
如需进一步阅读,您可能需要查看c++ I/O 参考
回答by user258808
To read you should create an instance of ifsteam and not ofstream.
要阅读,您应该创建一个 ifsteam 而不是 ofstream 的实例。
ifstream iusrfile;
You should open the file in read mode.
您应该以读取模式打开文件。
iusrfile.open("usrfile.txt", ifstream::in);
Also this statement is not correct.
此外,这种说法是不正确的。
cout<<iusrfile;
If you are trying to print the data you read from the file you should do:
如果您尝试打印从文件中读取的数据,您应该执行以下操作:
cout<<usr;
You can read more about ifstream and its API here
您可以在此处阅读有关 ifstream 及其 API 的更多信息