我正在使用cd切换到具有此程序的终端内部的目录。然后我运行make。我的make文件包括:
all:
gcc -Wall -Wpedantic -std=c99 *.c -o coolSort -pthread
然后我运行(小数据是包含文本文件的目录的相对路径):
./ coolSort小数据
我正在尝试使用相对或绝对路径名打开目录。然后,我尝试打开并读取刚打开的目录中任意数量的文件。
我收到的错误是“没有这样的文件或目录”。我已经在很多地方得到了这个,最近在以下if语句中得到了
if((dirp = opendir(argv[1])) == NULL) {
if(lstat(dirstructp->d_name, &buf) == -1) {
if ((dirEntry = fopen(dirstructp->d_name, "r")) == NULL) {
这是完整的代码:
#define _GNU_SOURCE
#define MAXPATHLENGTH 1024
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
typedef struct records {
char* username;
char* password;
char* bloodType;
char* domainName;
char* dbIndex;
} records;
int main(int argc, char** argv) {
if(argc != 2) {
printf("You must provide 2 arguments: <./filename> <directory>\n");
return -1;
}
char* path = malloc(MAXPATHLENGTH * sizeof(char));
char* cwd = malloc(MAXPATHLENGTH * sizeof(char));
FILE* sortedFile;
FILE* dirEntry;
DIR* dirp; //pointer to a directory stream
struct dirent* dirstructp; //pointer to a dirent structure
struct stat buf;
//changes the current working directory of the calling process to the directory specified
if((chdir(argv[1])) == -1) {
fprintf(stderr, "%s\n", strerror(errno));
exit(errno);
}
/*copies the pathname of the current working directory to the array pointed to by cwd, which is of length MAXPATHLENGTH*/
if((path = getcwd(cwd, MAXPATHLENGTH)) == NULL) {
fprintf(stderr, "%s\n", strerror(errno));
exit(errno);
}
//returns a pointer to the directory stream if successful
if((dirp = opendir(argv[1])) == NULL) {
fprintf(stderr, "%s\n", strerror(errno));
exit(errno);
}
/*On success, readdir() returns a pointer to a dirent structure (which may be statically allocated, so don't attempt to free(3) it) representing the next directory entry in the directory stream pointed to by dirp*/
while((dirstructp = readdir(dirp)) != NULL) {
/*retrieves information about the file pointed to by dirstructp->d_name; if dirstructp- >d_name is a symbolic link, then it returns information about the link itself, not the file that it refers to.*/
if(lstat(dirstructp->d_name, &buf) == -1) {
fprintf(stderr, "%s\n", strerror(errno));
exit(errno);
}
if(S_ISREG(buf.st_mode)) {
if ((dirEntry = fopen(dirstructp->d_name, "r")) == NULL) {
fprintf(stderr, "%s\n", strerror(errno));
exit(errno);
}
}
}
return 0;
}