【发布时间】:2021-09-09 16:24:22
【问题描述】:
我正在尝试制作一个简单的程序,列出目录中的所有 txt 文件,然后在其中附加 hello world,但在将向量传递给 WriteFiles 函数时遇到问题
这是我尝试修复它一段时间的以下代码,感谢任何帮助
#define _CRT_SECURE_NO_WARNINGS
#include <string>
#include <vector>
#include <iostream>
#include <windows.h>
#include <fstream>
using namespace std;
void ListFiles(vector<string>& f) // list all files
{
FILE* pipe = NULL;
string pCmd = "dir /b /s *.txt ";
char buf[256];
if (NULL == (pipe = _popen(pCmd.c_str(), "rt")))
{
return;
}
while (!feof(pipe))
{
if (fgets(buf, 256, pipe) != NULL)
{
f.push_back(string(buf));
}
}
_pclose(pipe);
}
void WriteFiles (const char* file_name)
{
std::ofstream file;
file.open(file_name, std::ios_base::app); // append instead of overwrite
file << "Hello world";
file.close();
}
int main()
{
vector<string> files;
ListFiles(files);
vector<string>::const_iterator it = files.begin();
while (it != files.end())
{
WriteFiles(*it); // the issue is here
cout << "txt found :" << *it << endl;
it++;
}
}
【问题讨论】:
-
尤达太多了。
FILE* pipe = _popen(pCmd.c_str(), "rt"); if (!pipe) return;. -
这并没有解决问题,而是养成使用有意义的值初始化对象的习惯,而不是默认构造它们并立即覆盖默认值。在这种情况下,这意味着将
std::ofstream file; file.open(file_name, std::ios_base::app);更改为std::ofstream file(file_name, std::ios_base::app);。此外,您不必致电file.close()。析构函数会这样做。 -
C++ 有一个文件系统库。我建议使用它而不是在
dir上捎带。