我正在编写一个程序,当它在一个目录中执行时将生成一个包含该目录中所有内容的文本文件。我正在获取从 **argv
到 main 的目录路径,因为我使用的是 netbeans 和 cygwin,所以我必须对 char* get_path( char **argv)
函数。目录路径大小将始终变化,因此我使用 malloc 分配空间以将其存储在内存中。
程序片段:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include "dbuffer.h" //my own library
#include "darray.h" //my own library
ARR* get_dir_contents( char* path)
{
DBUFF *buff = NULL;
ARR *car = NULL;
DIR *dir_stream = NULL;
struct dirent *entry = NULL;
dir_stream = opendir(path);
if(opendir(path)==NULL) printf("NULL");
//... more code here
return car;
}
char* get_path(char **argv)
{
char *path = malloc(sizeof(char)* sizeof_pArray( &argv[0][11] ) + 3 );
strcpy(path, "C:");
strcat(path, &argv[0][11]);
printf("%s, sizeof: %d \n",path, sizeof_pArray(path));
return path;
}
int main(int argc, char** argv)
{
char *p = get_path(argv);
ARR *car = get_dir_contents(&p[0]);
//... more code here
return (EXIT_SUCCESS);
}
问题是我的字符串没有初始化 dir_stream
指针。我怀疑这是因为指针和字符串文字之间存在一些差异,但我无法确定它到底是什么。此外,dirent 库函数需要 DIR *opendir(const char *dirname);
const char 可能与此有关。
输出:
C:/Users/uk676643/Documents/NetBeansProjects/__OpenDirectoryAndListFiles/dist/Debug/Cygwin_4.x-Windows/__opendirectoryandlistfiles, sizeof: 131
NULL
RUN FAILED (exit value -1,073,741,819, total time: 2s)
最佳答案
这里有些事情可能会出错,所以 我建议改为做这样的事情
char* get_path(char *argv)
{
char *path = malloc(sizeof(char)* strlen(argv) );
if (path != NULL)
{
strcpy(path, "C:");
strcat(path, argv + 11);
printf("%s, sizeof: %d \n",path, strlen(path));
}
return path;
}
...
char* p = get_path(*argv);
注意:您不需要额外的 3 个字节,因为您分配的包括稍后跳过的 11 个字节。尽管您可能不想使用 11 个字节的偏移量来分解字符串,然后将其放在一起以便于移植。例如。使用 strtok
您可以拆分该路径并替换您不需要的部分。
关于C - 获取目录路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32946676/