在 C++ 中的特定路径中写入文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9739948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write a file in a specific path in C++
提问by user840718
I have this code that writes successfully a file:
我有这个成功写入文件的代码:
ofstream outfile (path);
outfile.write(buffer,size);
outfile.flush();
outfile.close();
buffer and size are ok in the rest of code. How is possible put the file in a specific path?
其余代码中的缓冲区和大小都可以。如何将文件放在特定路径中?
回答by 111111
Specify the full path in the constructor of the stream, this can be an absolute path or a relative path. (relative to where the program is run from)
在流的构造函数中指定完整路径,这可以是绝对路径或相对路径。(相对于程序运行的位置)
The streams destructor closes the file for you at the end of the function where the object was created(since ofstream
is a class
).
流析构函数在创建对象的函数结束时为您关闭文件(因为ofstream
是 a class
)。
Explicit closes are a good practice when you want to reuse the same file descriptor for another file. If this is not needed, you can let the destructor do it's job.
当您想为另一个文件重用相同的文件描述符时,显式关闭是一种很好的做法。如果不需要,您可以让析构函数完成它的工作。
#include <fstream>
#include <string>
int main()
{
const char *path="/home/user/file.txt";
std::ofstream file(path); //open in constructor
std::string data("data to write to file");
file << data;
}//file destructor
Note you can use std::string in the file constructor in C++11 and is preferred to a const char* in most cases.
请注意,您可以在 C++11 的文件构造函数中使用 std::string,并且在大多数情况下比 const char* 更受欢迎。
回答by user1976
Rationale for posting another answer
发布另一个答案的理由
I'm posting because none of the other answers cover the problem space.
我发帖是因为其他答案都没有涵盖问题空间。
The answer to your question depends on how you get the path. If you are building the path entirely within your application then see the answer from @James Kanze. However, if you are reading the path or components of the path from the environment in which your program is running (e.g. environment variable, command-line, config files etc..) then the solution is different. In order to understand why, we need to define what a path is.
您的问题的答案取决于您如何获得路径。如果您完全在应用程序中构建路径,请参阅@James Kanze 的答案。但是,如果您从程序运行的环境(例如环境变量、命令行、配置文件等)中读取路径或路径的组成部分,那么解决方案就不同了。为了理解原因,我们需要定义路径是什么。
Quick overview of paths
路径的快速概览
On the operating systems (that I am aware of), a path is a string which conforms to a mini-language specified by the operating-system and file-system (system for short). Paths can be supplied to IO functions on a given system in order to access some resource. For example here are some paths that you might encounter on Windows:
在操作系统上(我知道),路径是一个字符串,它符合操作系统和文件系统(简称系统)指定的迷你语言。可以为给定系统上的 IO 函数提供路径以访问某些资源。例如,以下是您在 Windows 上可能会遇到的一些路径:
\file.txt
\bob\admin$\file.txt
C:..\file.txt
\?\C:\file.txt
.././file.txt
\.\PhysicalDisk1\bob.txt
\;WebDavRedirector\bob.com\xyz
C:\PROGRA~1\bob.txt
.\A:B
Solving the problem via path manipulation
通过路径操作解决问题
Imagine the following scenario: your program supports a command line argument, --output-path=<path>
, which allows users to supply a path into which your program should create output files. A solution for creating files in the specified directory would be:
想象一下以下场景:您的程序支持命令行参数 ,--output-path=<path>
它允许用户提供程序应在其中创建输出文件的路径。在指定目录中创建文件的解决方案是:
- Parse the user specified path based on the mini-language for the system you are operating in.
- Build a new path in the mini-language which specifies the correct location to write the file using the filename and the information you parsed in step 1.
- Open the file using the path generated in step 2.
- 根据您正在运行的系统的迷你语言解析用户指定的路径。
- 以迷你语言构建一个新路径,该路径使用文件名和您在步骤 1 中解析的信息指定写入文件的正确位置。
- 使用步骤 2 中生成的路径打开文件。
An example of doing this:
这样做的一个例子:
On Linux, say the user has specified --output-path=/dir1/dir2
在 Linux 上,假设用户已指定 --output-path=/dir1/dir2
Parse this mini-language:
解析这个迷你语言:
/dir1/dir2
--> "/" root
--> "dir1" directory under root
--> "/" path seperator
--> "dir2" directory under dir1
Then when we want to output a file in the specified directory we build a new path. For example, if we want to output a file called bob.txt
, we can build the following path:
然后当我们想输出指定目录中的文件时,我们建立一个新路径。例如,如果我们想输出一个名为 的文件bob.txt
,我们可以构建以下路径:
/dir1/dir2/bob.txt
--> "/" root
--> "dir1" directory under root
--> "/" path separator
--> "dir2" directory under dir1
--> "/" path seperator
--> "bob.txt" file in directory dir2
We can then use this new path to create the file.
然后我们可以使用这个新路径来创建文件。
In general it is impossible to implement this solution fully. Even if you could write code that could successfully decode all path mini-languages in existence and correctly represent the information about each system so that a new path could be built correctly - in the future your program may be built or run on new systems which have new path mini-languages that your program cannot handle. Therefore, we need to use a careful strategy for managing paths.
一般而言,完全实施此解决方案是不可能的。即使您可以编写代码来成功解码所有存在的路径迷你语言并正确表示有关每个系统的信息,以便可以正确构建新路径 - 将来您的程序可能会在具有以下功能的新系统上构建或运行您的程序无法处理的新路径迷你语言。因此,我们需要使用谨慎的策略来管理路径。
Path handling strategies
路径处理策略
1. Avoid path manipulation entirely
1. 完全避免路径操作
Do not attempt to manipulate paths that are input to your program. You should pass these strings directly to api functions that can handle them correctly. This means that you need to use OS specific api's directly avoiding the C++ file IO abstractions (or you need to be absolutely sure how these abstractions are implemented on each OS). Make sure to design the interface to your program carefully to avoid a situation where you might be forced into manipulating paths. Try to implement the algorithms for your program to similarly avoid the need to manipulate paths. Document the api functions that your program uses on each OS to the user - this is because OS api functions themselves become deprecated over time so in future your program might not be compatible with all possible paths even if you are careful to avoid path manipulation.
不要试图操纵输入到程序中的路径。您应该将这些字符串直接传递给可以正确处理它们的 api 函数。这意味着您需要直接使用操作系统特定的 api 来避免 C++ 文件 IO 抽象(或者您需要绝对确定这些抽象是如何在每个操作系统上实现的)。确保仔细设计程序的接口,以避免出现可能被迫操作路径的情况。尝试为您的程序实现算法,以类似地避免操作路径的需要。向用户记录您的程序在每个操作系统上使用的 api 函数 - 这是因为操作系统 api 函数本身随着时间的推移而被弃用,因此将来即使您小心避免路径操作,您的程序也可能无法与所有可能的路径兼容。
2. Document the functions your program uses to manipulate paths
2. 记录你的程序用来操作路径的函数
Document to the user exactly how paths will be manipulated. Then make it clear that it is the users responsibility to specify paths that will work correctly with the documented program behavior.
向用户记录如何操作路径。然后明确指出,用户有责任指定可以与记录的程序行为正确工作的路径。
3. Only support a restricted set of paths
3. 只支持一组受限的路径
Restrict the path mini-languages your program will accept until you are confident that you can correctly manipulate the subset of paths that meet this set of restrictions. Document this to the user. Error if paths are input that do not conform.
限制您的程序将接受的路径迷你语言,直到您确信您可以正确操作满足这组限制的路径子集。将此记录给用户。如果输入的路径不符合,则会出错。
4. Ignore the issues
4. 忽略问题
Do some basic path manipulation without worrying too much. Accept that your program will exhibit undefined behavior for some paths that are input. You could document to the user that the program may or may not work when they input paths to it, and that it is the users responsibly to ensure that the program has handled the input paths correctly. However, you could also not document anything. Users will commonly expect that your program will not handle some paths correctly (many don't) and therefore will cope well even without documentation.
做一些基本的路径操作而不用太担心。接受您的程序将显示某些输入路径的未定义行为。您可以向用户记录,当他们输入路径时,程序可能会或可能不会工作,并且用户有责任确保程序正确处理输入路径。但是,您也无法记录任何内容。用户通常会期望您的程序无法正确处理某些路径(很多都没有),因此即使没有文档也能很好地处理。
Closing thoughts
结束语
It is important to decide on an effective strategy for working with paths early on in the life-cycle of your program. If you have to change how paths are handled later it may be difficult to avoid a change in behaviour that might break the your program for existing users.
在程序生命周期的早期就决定使用路径的有效策略很重要。如果您以后必须更改路径的处理方式,则可能难以避免可能会破坏现有用户程序的行为更改。
回答by Gelo
Try this:
尝试这个:
ofstream outfile;
string createFile = "";
string path="/FULL_PATH";
createFile = path.as<string>() + "/" + "SAMPLE_FILENAME" + ".txt";
outfile.open(createFile.c_str());
outfile.close();
//It works like a charm.
回答by Nikolai Fetissov
That needs to be done when you open the file, see std::ofstream
constructoror open()
member.
回答by James Kanze
It's not too clear what you're asking; if I understand correctly, you're
given a filename, and you want to create the file in a specific
directory. If that's the case, all that's necessary is to specify the
complet path to the constructor of ofstream
. You can use string
concatenation to build up this path, but I'd strongly recommend
boost::filesystem::path
. It has all of the functions to do this
portably, and a lot more; otherwise, you'll not be portable (without a
lot of effort), and even simple operations on the filename will require
considerable thought.
你问的不是很清楚;如果我理解正确,您将获得一个文件名,并且您想在特定目录中创建该文件。如果是这种情况,所有需要的就是指定ofstream
. 您可以使用字符串连接来构建此路径,但我强烈建议使用
boost::filesystem::path
. 它具有可移植地执行此操作的所有功能,以及更多功能;否则,您将无法移植(无需付出太多努力),甚至对文件名的简单操作也需要深思熟虑。
回答by StackAttack
I was stuck on this for a while and have since figured it out. The path is based off where your executable is and varies a little. For this example assume you do a ls
while in your executable directory and see:
我被困在这个问题上一段时间,后来想通了。该路径基于您的可执行文件所在的位置,并且略有不同。对于此示例,假设您ls
在可执行目录中执行一段时间并查看:
myprogram.out Saves
Where Saves is a folder and myprogram.out is the program you are running.
其中 Saves 是一个文件夹, myprogram.out 是您正在运行的程序。
In your code, if you are converting chars to a c_str()
in a manner like this:
在您的代码中,如果您c_str()
以如下方式将字符转换为 a :
string file;
getline(cin, file, '\n');
ifstream thefile;
thefile.open( ("Saves/" + file + ".txt").c_str() );
and the user types in savefile, it would be
并且用户输入保存文件,它将是
"Saves/savefile.txt"
which will work to get to to get to savefile.txt in your Saves folder. Notice there is no pre-slashes and you just start with the folder name.
这将有助于到达 Saves 文件夹中的 savefile.txt。请注意,没有前斜杠,您只需从文件夹名称开始。
However if you are using a string literal like
但是,如果您使用的是字符串文字,例如
ifstream thefile;
thefile.open("./Saves/savefile.txt");
it would be like this to get to the same folder:
进入同一个文件夹是这样的:
"./Saves/savefile.txt"
Notice you start with a ./
in front of the foldername.
请注意,您以文件./
夹名称前面的a 开头。
回答by Tao Feng
If you are using linux, try execl(), with the command mv.
如果您使用的是 linux,请尝试使用命令 mv 执行 execl()。