【发布时间】:2017-11-03 21:20:38
【问题描述】:
我想将下面代码中变量name 中的数据保存到我的输出文件data.txt 似乎很容易?
不,因为我正在扫描 .exe 的根 "." 目录中的文件,然后将它们输出到 cmd 很容易,为什么我还要努力简单地输出到文件?
任何建议或意见将不胜感激。
原初处女code
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
#include <experimental/filesystem>
#include <fstream>
using namespace std;
std::vector<std::string> get_filenames(std::experimental::filesystem::path path)
{
namespace stdfs = std::experimental::filesystem;
std::vector<std::string> filenames;
const stdfs::directory_iterator end{};
for (stdfs::directory_iterator iter{ path }; iter != end; ++iter)
{
if (stdfs::is_regular_file(*iter))
filenames.push_back(iter->path().string());
}
return filenames;
}
void Dirloop(){
for (const auto& name : get_filenames(".")) std::cout << name << '\n';
}
void Outfile() {
std::ofstream outputFile("data.txt", std::ios::out);
outputFile << name << std::endl;
outputFile.close();
cout << "Generated data.txt!\n";
}
int main()
{
Dirloop();
Outfile();
std::getchar();
return 0;
}
【问题讨论】:
-
outputFile << name << std::endl;name来自哪里?很难就修复显然不可能的代码提出建议。 -
您在
DirLoop函数中声明了name,但您试图在Outfile中使用它。 -
更改
Outfile,使其将name作为参数,并从Dirloop调用它。它还应该以std::ios::app模式打开文件,以便每次都添加到文件中而不是覆盖它。
标签: c++ windows console-application