[英]Ofstream does create but doesn't write to file
Here is the code:这是代码:
void makefiles(char* filename) {
ifstream file(filename, ios::in);
// number of entries in main file
int size = 0;
// names is the vector that holds entries
vector<string> names;
string tmpstr;
while (getline(file, tmpstr)) {
string toadd = "";
for (int i = 0; i < tmpstr.size(); i++) {
if (tmpstr[i] != '|')
toadd += tmpstr[i];
else
break;
}
if(count(names.begin(), names.end(), toadd) == 0)
names.push_back(toadd);
size++;
}
file.close();
ofstream userfile;
file.open(filename, ios::in);
for (int i = 0; i < names.size(); i++) {
userfile.open(string(getenv("TEMP")) + "\\" + names[i] + ".txt", ios::out);
cout << string(getenv("TEMP")) + "\\" + names[i] + ".txt" << endl;
while (getline(file, tmpstr)) {
if (tmpstr.rfind(names[i], 0) == 0) {
userfile << tmpstr << endl;
userfile.flush();
}
}
userfile.close();
}
file.close();
}
This function is being called from main, filename contains some formatted text, like email database of the next view:这个 function 是从 main 调用的,文件名包含一些格式化的文本,比如下一个视图的 email 数据库:
gottaletitout@gmail.com|timetogo@gmail.com|06.01.2023|21:09:30|born in the abyss|156
gottaletitout@gmail.com|timetogo@gmail.com|06.01.2023|21:09:30|born in the abyss|156
a@gmail.com|b@gmail.com|23.12.2009|13:52:16|prikol|13
hottaletitout@gmail.com|timetogo@gmail.com|06.01.2023|21:09:30|aorn in the abyss|156
Thus, one line is one entry因此,一行是一个条目
In conclusion, I get many empty files that have the names i want, but, again, they are empty总之,我得到了许多具有我想要的名称的空文件,但是,它们又是空的
I tried adding right after opening userfile:我尝试在打开用户文件后立即添加:
if(!userfile){
cout << "File is not opened" << endl;
return;
}
But it doesn't help because !userfile = false但这无济于事,因为 !userfile = false
I tried instead of userfile << tmpstr << endl, using userfile << tmpstr << flush;我尝试使用 userfile << tmpstr << flush 代替 userfile << tmpstr << endl;
You are writing at most one file.您最多正在编写一个文件。 On the first iteration of the last
for
loop, with i==0
, the inner while
loop reads file
all the way to EOF.在最后一个
for
循环的第一次迭代中,当i==0
时,内部while
循环将file
一直读取到 EOF。 On all subsequent iterations, file
is already at EOF and all getline
calls fail immediately.在所有后续迭代中,
file
已经处于 EOF 并且所有getline
调用立即失败。 So all the files but the first (the one named after names[0]
) are created but never written to.因此,除了第一个文件(以
names[0]
命名的文件)之外的所有文件都已创建但从未写入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.