【问题标题】:C++ ofstream dynamic file names and contentC++ ofstream 动态文件名和内容
【发布时间】:2019-02-21 20:08:14
【问题描述】:

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

【问题讨论】:

  • 这并没有解决问题,而是养成使用有意义的值初始化对象的习惯,而不是使用它们的默认构造函数并立即更改它们。在这种情况下,这意味着ofstream file; file.open("./tmp/test.txt"); 应该是ofstream file("./tmp/test.txt");。此外,您无需致电file.close();。对象的析构函数会这样做。

标签: c++ file fstream naming ofstream


【解决方案1】:

如果this-&gt;tinfo.first_namestd::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 可以使用的任何数据类型。

Documentation for std::ostringstream

注意:可以使用 std::string 的文件 open 是在 C++11 中添加的。如果编译到较旧的标准,您将需要

file.open(temp.c_str());

【讨论】:

    【解决方案2】:

    这种情况你不需要%s,ofstream会隐式理解this-&gt;tinfo.first_name。所以请替换这一行

    file << "%s\n", this->tinfo.first_name;                     //nope %s->FUBAR
    

    通过

    file << this->tinfo.first_name << "\n";                     //nope %s->FUBAR
    

    【讨论】:

      【解决方案3】:

      我不明白你为什么要在 fstream 中使用 printf 语法。我只是建议使用ofstream,就像使用cout 一样。前任: file &lt;&lt; this-&gt;tinfo.first_name &lt;&lt; '\n';

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-20
        • 1970-01-01
        • 2018-11-18
        • 1970-01-01
        • 2010-09-24
        • 2011-10-26
        相关资源
        最近更新 更多