c - c 中的字符串连接分为两行

标签 c

我正在尝试连接两个字符串以用于 stat 函数,但是当我 strcat char* 然后打印时,它会像这样显示两行。

./
boot
tmp
./
tmp
lib
./
lib
lost+found
./
lost+found
sbin
./
sbin
etc

我已经尝试了一些方法,但我可能做错了。这是我的代码。

#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include <string.h>
#include <time.h>


int printDetails(char *path, char *name){
 struct stat fileInfo;
 char file[100];
 strcpy(file, path);
 strcat(file, name);

 printf("%s\n", file);

 return 1;
}


int main(int argc, char *argv[]) {
 struct dirent *direntp;
 DIR *dirp;

 printf("Please Enter directory path\n");
 char data[64];

 if (fgets(data, sizeof data, stdin)) {

   if ((dirp = opendir("/")) == NULL) {
      perror ("Failed to open directory");
      return 1;
   }   

   while ((direntp = readdir(dirp)) != NULL)
   {
      printf("%s\n", direntp->d_name);
      if(direntp->d_name != "." && direntp->d_name != ".."){
        printDetails(data, direntp->d_name);
      }
   }

   while ((closedir(dirp) == -1) && (errno == EINTR)) ;
 }
   return 0;
}

关于这个问题的任何帮助都会很棒。

非常感谢

最佳答案

fgets 将在每行末尾包含 \n 字符。也就是说,假设文本行不长于您传入的大小 - 否则您将只获得该行的一部分。

关于c - c 中的字符串连接分为两行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42419739/

相关文章:

c++ - 何时调用 PostQuitMessage

c++ - C/C++ : Float comparison speed

c - 使迭代器成为指针会加速 C 循环吗?

c - 神秘的P之谜

c - 无法在 automake 步骤上构建 spice

c - 将 C 结构传递给 OpenCL 内核

c - 为什么第二个 scanf() 不执行

c - 在 C 中使用 fopen 重复打开文件

c - For 循环没有执行预期的操作

c++ - 大型3D阵列性能: contiguous 1D storage vs T***