尝试使用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( "%s\n", this->tinfo.first_name); //nope this->FUBAR
file << "%s\n", this->tinfo.first_name; //nope %s->FUBAR
//Me->FUBU
file << "test\n";
file << "test\n";
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>
你不需要%s
这种情况,ofstream会隐含地理解this->tinfo.first_name
。所以请更换这一行
file << "%s\n", this->tinfo.first_name; //nope %s->FUBAR
通过
file << this->tinfo.first_name << "\n"; //nope %s->FUBAR
如果this->tinfo.first_name
是std::string
你可以将所有东西都附加到一个string
。
std::string temp = "./tmp/" + this->tinfo.first_name + ".txt";
file.open(temp);
如果没有,用string
建造一个std::stringstream
std::ostringstream temp;
temp << "./tmp/" << this->tinfo.first_name << ".txt";
file.open(temp.str());
应该处理%s
将使用的任何数据类型。
Documentation for std::ostringstream
注意:在C ++ 11中添加了可以使用open
的文件std::string
。如果要编译为旧标准,则需要
file.open(temp.c_str());
我不明白你为什么要在fstream中使用printf语法。我建议使用ofstream
,就像使用cout
一样。 E.X:file << this->tinfo.first_name << '\n';