0

老实说,我不知道这里发生了什么,但这是我的解释>

我 malloc 一个字符串数组来保存一个文件名数组,那里没问题。然后我进入一个 while 循环,它保持所有正确的值,直到它打印时间

time(&rawtime);
printf("It is now: %s\n\n",ctime(&rawtime)); 

然后我的价值观就消失了。在任何地方都找不到它们,我现在似乎有一个空数组。

这是其余的代码

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <dirent.h>
#include <limits.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{

  int i,j, directSize,start=0,flag=0, menu;
  size_t size;
  char path[1024];  //current working directory path
  char ** files;    //created to store the directory contents in an array of strings
  char buffer ;     //buffer holds menu selection
  time_t rawtime;


  //buffer = (char*) malloc(sizeof(char));
  files = (char**) malloc(sizeof(char*)+1);

  //allocating memory for strings
  for(i=0;i<50;i++)
  {
    files[i] =(char*) malloc(64*sizeof(char));
  }

  getcwd(path,size);

  pid_t child;
  DIR * d;
  struct dirent *de;

  d = opendir(".");

  i=0;

  while((de = readdir(d)))
  {
    files[i] = de->d_name;
    i++;
  }


  directSize = i;
  closedir(d);

  printf("file[0]: %s",files[0]);

  while(flag == 0)
  {
    printf("\nfiles[0]: %s\n",files[0]);    //works 

    printf("Current Working directory: %s\n", path);
    printf("\nfiles[0]: %s\nSize: %d\n",files[0],directSize);   //works

    time(&rawtime);
    printf("It is now: %s\n\n",ctime(&rawtime)); //problem area? 

    printf("files[0]: %s\nSize: %d\n",files[0],directSize);     //doesn't work
    printf("Files:\t\t0. (..)\n");

    for(i=start;i<start+4;i++)
      printf("\t\t%d. %s \n",i+1, files[i]);

    //formatted print for the command menu 
    printf("\nOperation:\tV View\n\t\tR Run\n\t\tP Previous Files\tN Next Files\n\t\tX Exit\t\t\tH Help\n");

    printf("\nCommand: ");
    scanf("%c", &buffer);
    getchar();
    //if(isalpha(buffer))
    //  strcpy(buffer,toupper(buffer));
    printf("command chosen is: %c\n",buffer);

    //if(buffer != "N" && buffer != "P" && buffer != "X")
    //{
    //  printf("File/Directory #: ");
    //  scanf("%d", &menu);
    //}

    if(buffer == 'E' || buffer == 'e')
      flag=flag+ 1; 

  }


  return 0;
}
4

1 回答 1

1

问题是您没有字符串的深层副本。

 while((de = readdir(d)))
  {
    files[i] = de->d_name;   /* you just made files[i] pointing to de->d_name, instead of
                              * copy the content to files[i].
                              */
    i++;
  }

所以之后closedir()libc会重用内部缓冲区,内容可能会被 的其他功能修改libc,然后你得到一个垃圾内容。用 . 替换它strcpy(files[i], de->d_name)

于 2012-09-22T09:32:29.230 回答