【发布时间】: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