c++sprintf函数和fstream来创建/检查文本文件

c++ sprintf function and fstream to create/check a text file

本文关键字:检查 文本 文件 创建 函数 fstream c++sprintf      更新时间:2023-10-16

为了为POS程序创建新的文本文件/检查文件是否已经存在,我在使用sprintf和fstream函数时遇到了一些问题。我不知道我是否做错了什么,因为同一组函数在我的代码中的其他地方运行良好。。。

这个特定的代码部分接受用户的输入来创建一个详细信息文件,名称由输入系统的名字和姓氏详细信息组成。由于某些原因,没有创建新文件。当我逐步完成该程序时,我可以看到custDtec变量中填充了正确的数据。我还包括了文件存在性检查,因为它可能与手头的问题有关,也可能与此无关。。。

Tony Mickel

    sprintf(custDetC,"%s%s.txt", firstName.c_str(), lastName.c_str());
    cout << custDetC << endl;
    FileEX = FileExists(custDetC);
    if (FileEX == true)
    {
        fopen_s(&custDetF,custDetC, "rt");
        fprintf(custDetF, "%s %sn", firstName, lastName);
        fprintf(custDetF, "$dn", phoneNo);
        fprintf(custDetF, "%s $sn", unitHouseNum, street);
        fprintf(custDetF, "%s %s %d", suburb, state, postCode);
        fclose(custDetF);
    }
    else
    {
        char *buf = new char[100];
        GetCurrentPath(buf);
        cout << "file " << custDetC << " does not exist in " << buf << endl;
    }
}
bool FileExists(char* strFilename) 
{
    bool flag = false;
    std::fstream fin;
    // _MAX_PATH is the maximum length allowed for a path
    char CurrentPath[_MAX_PATH];
    // use the function to get the path
    GetCurrentPath(CurrentPath);
    fin.open(strFilename, ios::in);
    if( fin.is_open() )
    {
        //cout << "file exists in " << CurrentPath << endl;
        flag = true;
    }
    else
    {
        //cout << "file does not exist in " << CurrentPath << endl;
        flag = false;
    }
    fin.close();
    return flag;
}

您打开文件似乎是为了读取,但您需要打开它进行写入。

fopen_s() 中使用"wt"而不是"rt"