【发布时间】:2015-10-05 10:44:20
【问题描述】:
我正在编写一个程序,当它在一个目录中执行时会生成一个包含该目录中所有内容的文本文件。我正在获取从 **argv 到 main 的目录路径,因为我使用的是 netbeans 和 cygwin,所以我必须在我的 char* get_path(char **argv) 函数中对获得的路径进行一些字符串操作。目录路径大小总是会有所不同,因此我使用 malloc 分配空间以将其存储在内存中。
程序sn-p:
#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)
【问题讨论】:
-
sizeof_pArray听起来不对,为什么不使用标准函数 strlen ?也不需要将**传递给get_path,只需将其声明为普通char*并传递*argv以使其更简单。 -
@CyberSpock 这是我自己的函数,它获取字符串长度 + 终止字符
-
如果
opendir()失败而不是printf("NULL")执行perror("opendir() failed")并且可能会明白出了什么问题。 -
如果你的程序是为 cygwin 构建的,你不应该尝试“本地化”路径。照原样使用它们。
opendir将在"/cygwin/c/Users/blah"上工作。
标签: c arrays string pointers malloc