C++流动态文件名和内容
C++ ofstream dynamic file names and content
尝试使用 fstream 编写动态文件名和内容,如下所示:
ofstream file;
file.open("./tmp/test.txt");
//file.open("./tmp/%s.txt.txt", this->tinfo.first_name); //nope file.open->FUBAR
//file.open("./tmp/" + this->tinfo.first_name + ".txt"); //nope this->FUBAR
//file.write( "%sn", this->tinfo.first_name); //nope this->FUBAR
file << "%sn", this->tinfo.first_name; //nope %s->FUBAR
//Me->FUBU
file << "testn";
file << "testn";
file.close();
我天真地认为 printf(%d,this->foo) 约定将起作用,如果不用于实际文件名,则适用于内容。
似乎什么都不起作用,我错过了什么?
以防万一它在我的包含:
#include "stdafx.h"
//#include <stdio.h> //redundant, as "stdafx.h" already includes it
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <iostream>
#include <fstream>
#include <string>
如果this->tinfo.first_name
是一个std::string
你可以将所有内容附加到一个string
。
std::string temp = "./tmp/" + this->tinfo.first_name + ".txt";
file.open(temp);
如果没有,请构建一个带有std::stringstream
的string
std::ostringstream temp;
temp << "./tmp/" << this->tinfo.first_name << ".txt";
file.open(temp.str());
应处理%s
将使用的任何数据类型。
标准::ostringstream 的文档
注意:可以在 C++11 中添加了可以使用std::string
的文件open
。如果编译到较旧的标准,您将需要
file.open(temp.c_str());
在这种情况下你不需要%s
,ofstream 会隐式理解this->tinfo.first_name
。所以请替换此行
file << "%sn", this->tinfo.first_name; //nope %s->FUBAR
由
file << this->tinfo.first_name << "n"; //nope %s->FUBAR
我不明白你为什么要在 fstream 中使用 printf 语法。我只是建议使用ofstream
,就像使用cout
一样。E.X:file << this->tinfo.first_name << 'n';
相关文章:
- 从命令行c++发送文本文件名
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- C++中的动态铸造故障
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 内联映射初始化的动态atexit析构函数崩溃
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 控制允许动态运行c++的并发操作数
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 在调用FreeLibrary后,释放动态链接到具有相同版本的CRT堆的DLL的内存
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 输出没有重复元素的动态数组(收缩数组)C++
- C++为线程工作动态地分割例程
- 正在插入动态数组
- 在c++中使用动态分配的问题
- 如何在C++中动态生成带有序列号的文件名
- text_multifile_backend如何设置文件名的动态日期
- C++流动态文件名和内容
- 如何在Arduino上为SD卡创建动态文件名