如何在 c++ 中访问同一文件夹中某些文件的内容
How to access to the content of some files in a same folder in c++?
我有一个文件夹,这个文件夹有 5 个文本文件。
我想阅读这些文本文件。
我知道通过这段代码,我可以在一个文件夹中拥有子文件夹的列表:
#include <dirent.h>
#include <stdio.h>
int main(void)
{
DIR *d;
struct dirent *dir;
d = opendir("c://myproject/task1");
if (d)
{
while ((dir = readdir(d)) != NULL)
{
printf("%sn", dir->d_name);
}
closedir(d);
}
return(0);
}
但是,我想读取这些文件(每个文件内容都是一个字符)并在屏幕上打印此字符。
所以我使用了这段代码:
int main(void)
{
DIR *d;
struct dirent *dir;
d = opendir("c://myproject/task1");
if (d)
{
while ((dir = readdir(d)) != NULL)
{
if(strcmp(dir->d_name,".")==0 || strcmp(dir->d_name,"..")==0 )
{continue;}
ifstream myReadFile;
myReadFile.open(dir->d_name);
char output;
if(myReadFile.is_open())
{
while (!myReadFile.eof())
{
myReadFile >> output;
cout<<output<<endl;
}
}
}
closedir(d);
}
return(0);
}
但是,我没有得到输出。
你能帮我找到代码中的问题吗?
您必须在
dir->d_name
之前连接folder_address
,而不是使用 strcat
myReadFile.open(dir->d_name);
。
因为dir->d_name
只有文件名,在可执行文件的当前路径中找不到,因此无法打开。
执行以下操作:
#include<dirent.h>
#include<iostream>
#include<fstream>
#include<string.h>
using namespace std;
int main(void)
{
DIR *d;
struct dirent *dir;
char folder_address[100];
strcpy(folder_address,"c://myproject/task1");
d = opendir(folder_address);
if (d)
{
while ((dir = readdir(d)) != NULL)
{
if(strcmp(dir->d_name,".")==0 || strcmp(dir->d_name,"..")==0 )
{continue;}
ifstream myReadFile;
char fname[200];
strcpy(fname, folder_address);
strcat(fname, "/");
strcat(fname, dir->d_name);
myReadFile.open(fname);
char output;
if (myReadFile.is_open())
{
while (1)
{
myReadFile >> output;
if(myReadFile.eof())
break;
cout<<output<<endl;
}
}
myReadFile.close();
}
closedir(d);
}
return(0);
}
问题是您在保留路径处打开一个文件夹:
d = opendir(folder_address); // I suppose folder_address is a string
但是您读取的d_name
包含文件名,而不是完整路径名。 因此,如果folder_address
不是当前目录,则打开将失败。
在尝试打开文件之前,您必须构建完整的路径名。 尝试类似操作:
string fullname(folder_address);
if (fullname.size()!=0)
fullname += "/"; // assuming it's posix
fullname += dir->d_name;
ifstream myReadFile(fullname);
char output;
if (myReadFile.is_open()) {
while (myReadFile>>output) { // loop on read (NEVER ON EOF in C++)
cout<<output<<endl;
}
}
重要说明:顺便说一下,您不应该循环 eOf,而是循环 C++ 流上的读取操作。
相关文章:
- 如何将更多文件夹添加到c++include路径
- 从对象文件(.o)在macos上制作归档文件(.a文件)
- 有没有办法读取C++中的文件文件夹?
- 错误C1083:无法打开包含文件.文件正确包含在代码中
- NDK 无法看到头文件 .h 文件
- 文件文件夹关联或归属
- 如何以阻止的方式删除文件/文件夹
- 在MFC中序列化为Unicode文本文件-文件头错误
- (Qt C++)如何从QTableView将所选文件/文件夹打印到文本文件中
- 获取带有POCO的服务可执行文件文件夹
- 如何从文件文件夹创建自定义文件类型
- 如何在windows7有限内存的电脑上读取大文件?文件大小为25GB,但RAM容量只有16GB
- c++以二进制方式读取文件.文件结束的问题
- 如何在linux的makefile中使用头文件(.h)文件中定义的宏定义
- 如何从文件夹中读取文件?文件夹包含不同类型的文件名
- 如何查找指向文件/文件夹的所有硬链接和符号链接(Windows和UNIX)
- 生成临时文件/文件夹 c++ GTEST
- 更改应用程序文件(. c文件)的名称
- 使用vc++2010从usb读取文件/文件夹
- 为特定的文件/文件夹禁用-Wall标志