在C 中重写文本文件
Rewriting a text file in c++
在处理文件流的程序上工作。我想编辑存储在文本文件中的文本行。据我了解,最好的方法是将所有内容从原始文件中复制,然后在新文件中重写它,从而使我的编辑沿途进行编辑。我无法在网上找到一个明确的示例,并且想知道我是否可以看到一个。
示例文本文件包含:
user1 pass1 55
user2 pass2 56
user3 pass3 57
我想编辑到它的位置:
user1 pass1 55
user2 pass2 44
user3 pass3 57
这是我的上下文删节代码:
#include <iostream>
#include <fstream>
using namespace std;
//function prototypes
void addUser();
void part1();
int main();
//global variables
string username;
string password;
int balance;
void addUser(){
//open a file in write mode
ofstream myfile;
myfile.open("userinfo.txt", ios::app);//append the text file
if(myfile.is_open()){
cout<<"Please Create a Username: ";
string inputCheck;//a string to compare name
cin>>inputCheck;
cout<<"Please Create a Password: ";
cin>>password;
cout<<"Current Balance: ";
cin>>balance;
myfile<<inputCheck<<' '<<password<<' '<<balance<<"n";
myfile.close();
cout<<"User account '"<<inputCheck<<"' has been created"<<endl;
}//ends create a password else
part1();
}
void part1()
{
cout<<"1.Add Usern2.Edit Information"<<endl;
int input;
cin>>input;
if(input == 1){
addUser();
}else if(input == 2){
//find the user
cout<<"Enter the username: ";
string checkUser;
cin>>checkUser;
ifstream infile("userinfo.txt"); //CREATING IFSTREAM
ofstream outfile("pleasework.txt");
bool foundUser = false;
while(infile>>username>>password>>balance){
if(checkUser==username){
foundUser = true;
break;
}
}
if(foundUser){
cout<<"Current Balance: "<<balance<<endl;
cout<<"Enter new balance: ";
int newBalance;
cin>>newBalance;
if(infile.is_open()){
outfile<<username<<' '<<password<<' '<<newBalance<<endl;
//How do I get all of the other unedited accounts in here?!?!?!?!
}
}//end input 2
infile.close();
outfile.close();
}
}//end part 1
int main(){
part1();
}
这是一些可能会有所帮助的伪代码:
方法1:
open existing file in 'read' mode
open new file in 'write' mode
for each line in existing:
if line doesn't need update:
write line to new file
else:
make changes to values from line
write updated line to new file
close existing file
close new file
move new file over existing file
方法2:
open existing file in 'read/write' mode
data = array of lines
for each line in existing:
read values into data
clear existing file
add/delete rows in data if necessary
for each row in data:
update values in row
write updated line to existing file
close existing file
呼叫
main();
递归使您拥有不确定的行为。因此,您无法可靠地期望任何事情。
相关文章:
- 文本文件中的单词链表
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何在c++中从文本文件中逐行读取整数
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- C++试图读取一个文件并输出到另一个文本文件
- 如何通过套接字将文本文件的内容从服务器发送到客户端
- 已修改的LinkedList未在文本文件本身中更新
- C++文本文件的获取线
- 为什么C++的文件 I/O 在读取文本文件时忽略初始空行?我怎样才能让它不这样做?
- 打印逐行存储的文本文件
- C++文本文件输入