C++流动态文件名和内容

C++ ofstream dynamic file names and content

本文关键字:文件名 动态 C++      更新时间:2023-10-16

尝试使用 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::stringstreamstring

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';