【发布时间】:2017-10-19 11:17:41
【问题描述】:
我想读取在可执行文件所在的文件夹中可以找到的所有文件,但我正在运行的可运行文件除外。我编写了以下代码,但是,尽管此列表正确列出了我文件夹中的文件,但我无法使用 fopen 打开它们,因为 fopen 打印出该文件不存在。如果我执行 gedit “从我的 c 程序中获得的文件的路径”,那么它会从该术语完美打开。错误在哪里?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
int main (int argc, char **argv) {
//Determining the number of files we have.
//We call to a bash command http://stackoverflow.com/questions/646241/c-run-a-system-command-and-get-output
FILE *fp, *fin;
char path[1035], cwd[1024];
int scanned = 0;
/* Open the command for reading. */
//https://askubuntu.com/questions/370697/how-to-count-number-of-files-in-a-directory-but-not-recursively
//This count soft and hard links also (I think)
fp = popen("ls -F |grep -v /", "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit(1);
}
/* Read the output a line at a time - output it. */
//Loop for each file. Be careful! if the exe is inside, it will also be counted!
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("Reading file: %s\n", path);
fin=fopen(path,"r");
scanned = 0;
printf("caa");
if (fin != NULL){
printf("AA\n");
fclose(fin);
}
if (!fin)perror("fopen");
printf("Done! \n");
}
/* close */
pclose(fp);
printf("end");
return 0;
}
【问题讨论】:
-
试试
printf("Reading file [%s]\n", path);。 -
fopen不打印任何东西! -
解析
ls输出是开销(进程创建、I/O)、脆弱(ls可能丢失或版本不兼容)并且容易出错(请参阅您的问题)- 建议您使用您平台的 API 处理此类事情,请参阅opendir()和readdir() -
另外,不需要
sizeof(path) - 1。只需使用sizeof(path)。 -
你可以——而且可能应该——避免使用你的
popen;请参阅readdir(3)、stat(2)、nftw(3)... 并阅读Advanced Linux Programming