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

问题描述 投票:-1回答:3

尝试使用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> 
c++ file fstream naming ofstream
3个回答
0
投票

你不需要%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

1
投票

如果this->tinfo.first_namestd::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());

0
投票

我不明白你为什么要在fstream中使用printf语法。我建议使用ofstream,就像使用cout一样。 E.X:file << this->tinfo.first_name << '\n';

© www.soinside.com 2019 - 2024. All rights reserved.