在c++中动态地将文件放在文件夹中

Put files in a folder dynamically in c++

本文关键字:文件夹 文件 c++ 动态      更新时间:2023-10-16

假设我有一个txt文件,在txt文件中写着:"doc1.doc,doc2.doc,doc3.doc"等。在我的代码中,我阅读了这个txt文件,找到了文档"doc1.doc,doc2.doc…".

我想在阅读txt文件时,用c++将这些文档文件放在一个文件夹中。有可能吗?

假设我已经有了一个文件夹,不需要创建新的文件夹。唯一需要考虑的是将文件放入文件夹。

编辑:我使用的是linux。

您可以使用Giomm,它是glibmm的一部分,是Glib的C++绑定。看一看,非常直观(超过低级系统/posix C功能):

http://developer.gnome.org/glibmm/stable/classGio_1_1File.html#details

这个可能对目录迭代有用:

http://developer.gnome.org/glibmm/stable/classGlib_1_1Dir.html

它也是便携式的!它将适用于Glib工作的任何地方。Windows、Linux、MacOS。。。您不会局限于linux。这确实意味着你依赖于Glim和glibmm,但Glib在GNU/Linux软件中非常常见,任何使用GTK或其任何绑定的GUI应用程序都会加载Glib,因此很可能,根据你的情况,这个解决方案并没有真正添加额外的依赖项。

此外,一个很大的优势,尤其是在使用Linux的情况下,是你可以访问免费软件的源代码,看看代码在那里做什么。例如,您可以访问git.Gnome.org上的Gnome的git存储库,然后转到一个使用文档的项目,例如文本编辑器gedit,并了解它如何将文档保存到文件中。或者更好的是,检查一个用C++编写的项目(gedit是用C编写的),比如Glom、Inkscape或Gnote,看看它们做了什么

您的问题没有提供足够的信息来获得完整的答案。作为一种语言,C++并没有真正的函数来处理文件夹或文件。这是因为C++与平台无关,这意味着你可以编译C++代码在Windows、MacOS、iOS、Android、Linux或任何其他没有文件系统的设备上运行。

当然,在您的案例中,您可能指的是Windows或Linux。如果是这种情况,那么,根据是哪一个,您可以使用文件系统功能在文件系统中复制或移动文件。

对于Windows,Win32 API具有用于复制文件的CopyFile和CopyFileEx函数,以及用于移动或重命名文件的MoveFile和MoveFileEx函数。

对于Linux,您可以使用sendfile API函数来使用内核复制文件。

我应该指出,可以用C/C++编写一些与平台无关的代码,使用打开/读取/写入功能将文件的内容复制到另一个文件中(即在读取模式下打开源文件,在写入模式下打开目标文件,然后继续从源文件读取并写入目标文件,直到到达源文件的末尾),但其他文件系统功能如果没有特定于平台的库,即使不是不可能,也很难进行复制。

更新

由于您指定了要在linux中执行此操作,以下是如何使用sendfile函数:

int inputFileDesc;
int outputFileDesc;
struct stat statBuffer;
off_t offset = 0;
// open the source file, and get a file descriptor to identify it later (for closing and sendfile fn)
inputFileDesc = open ("path_to_source_file", O_RDONLY);
// this function will fill the statBuffer struct with info about the file, including the size in bytes
fstat (inputFileDesc, &statBuffer);
// open the destination file and get a descriptor to identify it later (for closing and writing to it)
outputFileDesc = open ("path_to_destination_file", O_WRONLY | O_CREAT, statBuffer.st_mode);
// this is the API function that actually copies file data from source to dest;
//   it takes as params the descriptors of the input and output files and an offset and length for the amount of data to copy over
sendfile (outputFileDesc, inputFileDesc, &offset, statBuffer.st_size);
close (outputFileDesc);    // closes the output file (identified by descriptor) 
close (inputFileDesc);     // closes the input file (identified by descriptor)