尝试学习c++中的基本文件操作
Trying to learn basic file manipulation in c++
我正在努力掌握在C++
中处理文件的窍门。我正在尝试从一个文件中读取并制作另一个具有相同内容的文件。我已经成功地做到了可以复制文件的第一行,但不能复制其余的行。有人能告诉我我做错了什么吗?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char * argv[]){
string line;
ofstream writeFile;
ifstream readFile;
readFile.open("students.txt");
if (readFile.is_open()){
while (getline (readFile, line)){
writeFile.open("copytext.txt");
writeFile << line;
writeFile << line;
writeFile << line;
writeFile << line;
}
}
readFile.close();
writeFile.close();
return 0;
}
默认情况下,如果不指定标志,则openmode
将为write
。这将销毁文件的内容(如果该文件已存在)。
#include <iostream>
#include <fstream>
int main()
{
std::ofstream of("test.txt"); // close() implicitly called by destructor
}
> echo "hello" > test.txt
> cat test.txt
hello
> g++ test.cpp
> ./a.out
> cat test.txt
哎呀!
你显然应该把它移到循环之外。顺便说一句,您不需要显式调用open
或close
,因为构造函数和析构函数将分别调用它们。流对象也可以隐式转换为bool(如果流中有错误,则返回false),从而使is_open
成为冗余。
int main(int argc, char * argv[]){
string line;
ifstream readFile("students.txt");
ofstream writeFile("copytext.txt");
if (readFile && writeFile){
while (getline (readFile, line)) {
writeFile << line;
}
}
}
根据此链接,无法再次打开同一个文件并导致失败,如设置failbit
所示。所需的输出文件应该只打开一次。
我可以从您的代码重写的最简单方法
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char * argv[]){
string line;
ofstream writeFile;
ifstream readFile;
readFile.open("students.txt");
writeFile.open("copytext.txt",std::fstream::out);
if (readFile.is_open()){
while (getline (readFile, line)){
writeFile << line;
}
}
readFile.close();
writeFile.close();
return 0;
}
打开流时,您可以使用打开模式:std::fstream::in或std::fstream:
这将适用于
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char * argv[]){
string line;
ofstream writeFile;
ifstream readFile;
readFile.open("students.txt");
writeFile.open("copytext.txt");
if (readFile.is_open()){
while (getline (readFile, line))
{
writeFile << line << "n";
}
}
readFile.close();
writeFile.close();
return 0;
}
其中一个问题是您试图在while循环中打开"copytext.txt"。你还试着写了4次相同的文本,这是不必要的。
相关文章:
- C++二进制文件 I/O 操作速度变慢.数据库如何处理二进制文件?
- 程序未正确执行文件操作
- C++程序在执行文件操作时在Windows与Linux上运行得慢得多?
- 使用文件操作的 XMLFile 解析
- iOS和Android的C 中的文件操作
- 高级 I/O 文件操作,带函数
- 在Linux和Windows C 上处理的低级文件操作
- 如何使用QT Designer?实施最新的文件操作
- c++中的文件操作
- 二进制与文本模式下的文件操作 -- 性能问题
- 在Windows Server 2008上挂接SMB文件操作
- 尝试学习c++中的基本文件操作
- 内核授权文件操作范围在小牛队中已损坏
- 写入文件挂钩未捕获写入文件操作
- 每个目标的生成文件操作
- 文件 I/O 操作 - 奇怪的字符输入
- 是否需要为C/C++中的文件I/O操作创建自己的缓冲区
- C++文件操作
- 使用什么样的API,您可以在OSX中执行read-consistent文件操作,类似于Windows卷影服务
- 更快的文件操作C++