c++ - Ofstream 没有正确创建新文件

标签 c++ visual-studio-2012 creation ofstream

我尝试编写一个简单的数据库程序。问题是 ofstream 不想创建新文件。

这是违规代码的摘录。

void newd()
{
string name, extension, location, fname;
cout << "Input the filename for the new database (no extension, and no backslashes)." << endl << "> ";
getline(cin, name);
cout << endl << "The extension (no dot). If no extension is added, the default is .cla ." << endl << "> ";
getline(cin, extension);
cout << endl << "The full directory (double backslashes). Enter q to quit." << endl << "Also, just fyi, this will overwrite any files that are already there." << endl << "> ";
getline(cin, location);
cout << endl;
if (extension == "")
{
    extension = "cla";
}
if (location == "q")
{
}
else
{
    fname = location + name + "." + extension;
    cout << fname << endl;
    ofstream writeDB(fname);
    int n = 1; //setting a throwaway inteher
    string tmpField, tmpEntry; //temp variable for newest field, entry
    for(;;)
    {
        cout << "Input the name of the " << n << "th field. If you don't want any more, press enter." << endl;
        getline(cin, tmpField);
        if (tmpField == "")
        {
            break; 
        }
        n++;
        writeDB << tmpField << ": |";
        int j = 1; //another one
        for (;;)
        {
            cout << "Enter the name of the " << j++ << "th entry for " << tmpField << "." << endl << "If you don't want any more, press enter." << endl;
            getline(cin, tmpEntry);
            if (tmpEntry == "")
            {
                break;
            }
            writeDB << " " << tmpEntry << " |";
        }
        writeDB << "¬";
    }
    cout << "Finished writing database. If you want to edit it, open it." << endl;
}
}

编辑:好的,刚试过

#include <fstream>
using namespace std;
int main()
{
ofstream writeDB ("C:\\test.cla");
writeDB << "test";
writeDB.close();
return 0;
}

那没有用,所以是访问权限问题。

最佳答案

ofstream writeDB(fname); //-> replace fname with fname.c_str()

如果你查找 ofstream 构造函数的文档,你会看到类似这样的内容: 显式 ofstream (const char * filename, ios_base::openmode mode = ios_base::out);

第二个参数是可选的,但第一个参数是 const char*,而不是字符串。要解决这个问题,最简单的方法是将字符串转换为 C 字符串(char*,基本上是一个字符数组);为此,只需使用 c_str()(它是库的一部分)。

除此之外,您可以直接将信息放在 C-str 上,然后将其正常传递给 ofstream 构造函数。

关于c++ - Ofstream 没有正确创建新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13369541/

相关文章:

assembly - x86 程序集 "push OFFSET ..."和助记符?

c# - 以编程方式创建 'SharePoint Solution'

c++ - 对象的链表?

c++ - 使用友元函数和普通公共(public)函数时的行为差异

entity-framework - 将 EF Code First 同步到 SQL Azure

file - 重命名和重新创建文件时出现奇怪的时间戳重复

Python 文件创建日期和重命名 - 请求批评

c++ - 在 C++ 中读取/写入大文件的性能问题

python - 如何将 FFI 数组作为 c_void 指针传递给 nalgebra 的 DMatrix2?

visual-studio-2012 - 如何在 Pre-Build Event 中使用 $(OutDir)?