所以我创建了一个简单的测试应用程序。它的目的是读取或写入文本文件。它正在寻找字符串“固件:”。这个想法是设备将有一个包传输到它并存储,然后激活。我想存储该包的名称(例如:Update1),当我需要时,查询它并取回包名(从文件中读取)。
问题 1:它似乎没有写入文件。 问题2:当我让它写入文件时,如果存在“Firmware:pkgName”行,我如何将pkgName替换为新的包名?
该程序可以运行和编译,因此请随意将其放入 IDE 或文本编辑器中,但它并不能完全满足我的要求。我使用 log.txt 作为我的示例文件来读取。我确信有一种更简单的方法可以做到这一点。我已经有一段时间了,我已经被难住了。
谢谢您的帮助!
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int writeFile(string filename, string pkgName);
int readFile(string filename);
int main(void) {
string filename = "log.txt", userInput, pkgName;
system("touch log.txt");
while (true) {
cout << "Write or Read?\n>>>";
cin >> userInput;
if (userInput == "Write") {
cout << "What's your package name?\n>>>";
cin >> pkgName;
writeFile(filename, pkgName);
} else if (userInput == "Read") {
readFile(filename);
} else {
cout << "Invalid Input";
}
}
}
int writeFile(string filename, string pkgName) {
bool found, exists = true;
string line, word;
fstream firmwareFile;
int pos, size, num = 1;
firmwareFile.open(filename.c_str(), ios::in | ios::out | ios::app);
//firmwareFile << "This is a test.";
if (firmwareFile.is_open()) {
while (!found) {
getline(firmwareFile, line);
pos = line.find("Firmware: ");
if (pos != string::npos) {
//Found It
found = true;
exists = true;
size = line.size();
word = line.substr(10, ((size - pos) + 10));
cout << word << " is the old package name" << endl;
//TODO - Replace that with the new package name
firmwareFile.close();
} else if (firmwareFile.eof()) {
//Doesn't Exist
found = true;
exists = false;
cout << "No last firmware package available.\n";
} else {
//Still Looking
found = false;
cout << "Searching line #" << num << endl;
}
num++;
if (!exists) {
firmwareFile << endl << "Firmware: " << pkgName << endl;
cout << "Wrote package name to file\n" << endl;
}
firmwareFile.close();
}
} else {
cout << "Unable to open file";
}
}
int readFile(string filename) {
bool found;
string line, word;
fstream firmwareFile;
int pos, size, num = 1;
firmwareFile.open(filename.c_str(), ios::in | ios::out | ios::app);
if (firmwareFile.is_open()) {
while (!found) {
getline(firmwareFile, line);
pos = line.find("Firmware: ");
if (pos != string::npos) {
found = true;
size = line.size();
word = line.substr(10, ((size - pos) + 10));
cout << word << endl;
} else if (firmwareFile.eof()) {
found = true;
cout << "No last firmware package available.\n";
firmwareFile << endl << "Firmware: ";
} else {
cout << "Searching line #" << num << endl;
}
num++;
}
firmwareFile.close();
} else {
cout << "Unable to open file";
firmwareFile.close();
}
firmwareFile.close();
}
这是我的 log.txt 文件的内容(除了包含“固件:”的行之外的所有内容都是微不足道的)
You
Think
It's
Here
But
It's
Not
So
That
Sucks
Doesn't
It
?
Firmware: Update1
I
Hope
You
Caught
It
!