繁体   English   中英

C-获取数字而不是字符串

[英]C - Getting numbers instead of string

我正在使用dirent.h来查看var/log所有文件,并且希望将它们保存在数组中,但是当我保存它们时,它看起来像数字而不是字符串。 为什么会这样呢?

代码在这里:

  char *word = ".gz" ; 
  char *word2 = ".";
  char *word3 = "..";
  DIR           *directory;
  struct dirent *dir;

  directory = opendir("/var/log");
  if (directory)  {
    while ((dir = readdir(directory)) != NULL)
    {
      if((strstr(dir->d_name, word) == NULL) && (strstr(dir->d_name, word2) == NULL) && (strstr(dir->d_name, word3) == NULL)) {
      printf("%s\n", dir->d_name);
      i++;
      }
    }
      printf("%d\n",i);

    closedir(directory);
  }
  char *array_of_files[i];
  i=0;
  directory = opendir("/var/log");
  if (directory)  {
    while ((dir = readdir(directory)) != NULL)
    {
      if((strstr(dir->d_name, word) == NULL) && (strstr(dir->d_name, word2) == NULL) && (strstr(dir->d_name, word3) == NULL)) {
      array_of_files[i]=dir->d_name;
      printf("%d array of file \n",array_of_files[i]);
      i++;
      }
    }
      printf("%d\n",i);
     int j;
     for (j=0;j<i;j++){

        printf("%d ", array_of_files[j]);
     }
    closedir(directory);

首先,我使用一个计数器来计算文件夹中文件的数量,然后重新打开目录并使用该计数器创建数组,然后开始将文件名保存在文件夹中,但只显示数字。

一个例子:

./program

speech-dispatcher
dbconfig-common
apache2
mdm
fsck
samba
aptitude
dmesg
unattended-upgrades
postgresql
udev
installer
cups
hp
btmp
ConsoleKit
syslog
wtmp
mysql
lastlog
23
8962131 8962163 8962283 8962315 8962675 8962755 8962947 8963091 8963155 8963331 8963403 8963539 8963579 8963691 8963755 8964251 8964307 8964435 8964507 8964539 8964571 8964627 8964723

我知道有一种更好的方法来处理数组,而不是两个while循环,但是我现在想不出更好的方法。 如果您可以推荐一些东西,将不胜感激。

更改以下行

printf("%d array of file \n",array_of_files[i]); to 
printf("%s array of file \n",array_of_files[i]);`

printf("%d ", array_of_files[j]); to 
printf("%s ", array_of_files[j]);

使用@SAN回答的正确格式。

复制指针的作用不大,因为在dir->d_name调用之间可能会重新填充dir->d_name
代码需要创建和管理字符串副本。

char *array_of_files[i];
...
  while (...
    // array_of_files[i] =dir->d_name;
    array_of_files[i] = strdup(dir->d_name);
    ...
  }
}

for (j=0;j<i;j++){
  // printf("%d ", array_of_files[j]);
  printf("%s ", array_of_files[j]);
  free(array_of_files[j]);
}

如果您的系统没有strdup() ,则可以轻松创建自己的系统

你应该用

   printf("%c ", array_of_files[j]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM