【问题标题】:Opening a file from specified folder inside dir. where .exe is从 dir 中的指定文件夹打开文件。 .exe 在哪里
【发布时间】:2013-06-28 21:34:00
【问题描述】:

我需要帮助打开一个名为“编辑数据”的文件夹中的文件,该文件夹与我正在制作的 .exe 位于同一文件夹中。我不确定如何在 C++ 中处理从文件夹打开文件。 我想要的例子。

....\Program\Edit Data

....\Program\program.exe

我需要这样做,因为我在此文件夹中有多个用户可以编辑的文件。 我首先尝试为 Mod.dat 使用名为 Mod 的文件夹,但没有成功。

我当前代码的一半:

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cmath>
#include <cstring>

using namespace std;


int main ()
{


string filename;//file that will be changed
//string path = "Mod/Mod.dat";//Path of Mod.dat that I could not get to work
//string file = path + "Mod.dat";//this was for opinging Mod.dat from folder call Mod, didnt work
long size;
char* memblock;
cout << " Enter a file to be modded by Mod.dat  ";
cin >> filename;

ofstream infile ( filename ,std::ofstream::binary | ofstream::in);//the file that will be opened and changed)
//"filename: I want to open it from a folder called Edit Data

ifstream modFile ( "Mod.dat" , ifstream::binary);// (mod.dat is the file that i get the first 1840 hex values from)

if (!infile){
    cout << " Couldn't open " << filename << endl;
}

if (!modFile){
    cout << " Couldn't open " << modFile << endl;
}

我不知道这是否重要,但我使用 Visual Studios,我的程序会打开“infile”并对其进行编辑。 我还想从 Edit Data 文件夹中打开大约 1000 个文件,并使用 mod.dat 对其进行编辑。 (编辑:到目前为止,我主要只需要知道如何从文件夹中读取单个文件。) 还有一种方法可以让我制作一个带有文件名和位置的文本文档,当我将它添加到循环内部时,ofstream 读取的文件名和位置?

文件的外观: ....\程序\编辑数据\12a.dat ....\程序\编辑数据\m9i3.dat ....\Program\Edit Data\2020.dat

【问题讨论】:

    标签: c++ file location directory


    【解决方案1】:

    您可以使用 dirent.h 获取 Edit Data 文件夹中所有文件的数组,然后打开 *.dat 文件。

    或者您可以在 X 位置打开一个文件,其中包含您要编辑的文件及其文件路径的列表,请记住路径要么是完整的(“C:\Program Files\Edit Data”),要么是变量,例如作为(“..\编辑数据”)。

    【讨论】:

    • 如果我要写的话,这个“C:\Program Files\Edit Data”是否允许我访问该文件:“C:\Program Files\Edit Data(要编辑的文件)。日期”?
    • 问题是您要么事先知道文件的名称,要么通过从用户(cin 或 getline)获取的参数给出它。如果您不这样做,则必须使用文件系统库来搜索文件,这就是 dirent.h 的用途(或者您可以使用 fseek),您也可以使用 boost 文件系统。对文件的访问取决于您程序的权限,如果您以管理员身份运行它,您应该没有问题。
    • 好的,我刚刚得到了 dirent.h,我将尝试一下。现在我很多人专注于打开一个文件,我什至可以这样做。
    • 它的接缝我无法让 dirent.h 工作,我也不确定它是如何工作的。
    猜你喜欢
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    相关资源
    最近更新 更多