如何制作一个可以处理 .txt 文件而不显示它的 C++ 程序

How to make a C++ program that works with a .txt file without showing it

我的程序需要使用隐藏的文本文件来跟踪用户名。

但是当程序启动时,如果在同一目录下找不到'Name.txt'文件,它会生成一个用户可见的文件。

用户可以查看、编辑等。我怎样才能防止这种情况发生,以便只有我的程序可以修改文件?

此外,是否有更好的方法来了解用户的姓名(请记住,我是一般编程的新手,而不仅仅是 C++)?

#include "stdafx.h"
#include <fstream>
#include <iostream>
#include <string>
#include <Windows.h>

using std::string;
using std::cout;
using std::cin;
using std::ifstream;
using std::ofstream;

int main()
{
    string line;
    ifstream example;
    example.open("Name.txt");
    getline(example, line);
    if (line.compare("") == 0)
    {
        example.close();
        string con;
        cout << "Welcome to this program!\n";
        cout << "Do you want to register? (y/n) ";
        cin >> con;
        con[0] = tolower(con[0]);
        if (con.compare("n") != 0)
        {
            string name;
            ofstream one;
            one.open("Name.txt");
            cout << "What's your name? ";
            cin >> name;
            one << name;
            one.close();
            cout << "See you later " << name << ".";
            Sleep(4000);
        }
    }
    else
    {
        cout << "Welcome back " << line << ".";
        example.close();
        Sleep(4000);
    }
}

编辑:我刚刚意识到我说的是 'to keep track of the user'。现在我明白了为什么你们认为我想用这个程序做坏事。我现在更正了,我的意思是 'to keep track of the user’s name'.

我知道您想维护一个文件,其中包含所有注册用户的姓名,或其他一些与当前用户无关的数据。

问题

您的代码尝试打开程序当前工作目录中的文件。不幸的是,这取决于用户启动程序的方式。

它还会忽略读取文件时打开过程中可能出现的错误。因此,如果文件不存在,您的代码将打开文件作为 ofstream 进行写入(如果文件不存在,它将创建文件)。

如何解决?

为满足您的要求,您应该在预定位置打开文件(例如在安装过程中固定的位置,或在程序的配置中固定的位置)。请参阅 this article,了解在 windows 平台上理想地存储数据和配置文件的位置。

如果您想确保程序仅在文件已存在时打开该文件,您应该验证 ifstreamopen 的结果,如果失败则发出错误消息:

example.open("Name.txt");
if (!example) {
    cout << "OUCH ! Fatal error: the registration file couldn't be opened !" <<endl; 
    exit (1);     
}

如何保护文件免受用户攻击?

但是请注意,如果您的程序从文件中读取和写入数据,用户也可以找到它并手动编辑它。这将很难预防。

或者,您可以考虑使用 windows registry,这对用户来说更容易编辑(尽管并非不可能)。这种方法的主要不便在于它依赖于系统,并且会使您的代码移植到其他平台更加困难。

如果你想完全保护你的文件,你可以按照克里斯在评论中的建议,加密文件。加密是一项复杂的业务;考虑使用 openssl or a proven algorithm 这样的库。

这将保护您免受普通用户的侵害。但是您仍然会接触到能够对您的代码进行逆向工程并找到必须以某种方式嵌入到您的代码中以解密文件的加密密钥的黑客。