【发布时间】:2010-04-01 00:16:05
【问题描述】:
这是我检查文件是否存在的代码:
#include<stdio.h>
#include<zlib.h>
#include<unistd.h>
#include<string.h>
int main(int argc, char *argv[])
{
char *path=NULL;
FILE *file = NULL;
char *fileSeparator = "/";
size_t size=100;
int index ;
printf("\nArgument count is = %d", argc);
if (argc <= 1)
{
printf("\nUsage: ./output filename1 filename2 ...");
printf("\n The program will display human readable information about the PNG file provided");
}
else if (argc > 1)
{
for (index = 1; index < argc;index++)
{
path = getcwd(path, size);
strcat(path, fileSeparator);
printf("\n File name entered is = %s", argv[index]);
strcat(path,argv[index]);
printf("\n The complete path of the file name is = %s", path);
if (access(path, F_OK) != -1)
{
printf("File does exist");
}
else
{
printf("File does not exist");
}
path=NULL;
}
}
return 0;
}
在运行命令时 ./output test.txt test2.txt 输出是:
$ ./output test.txt test2.txt
Argument count is = 3
File name entered is = test.txt
The complete path of the file name is = /home/welcomeuser/test.txt
File does not exist
File name entered is = test2.txt
The complete path of the file name is = /home/welcomeuser/test2.txt
File does not exist
现在系统上确实存在 test.txt:
$ ls
assignment.c output.exe output.exe.stackdump test.txt
然而 test.txt 显示为一个不存在的文件。
请帮助我理解这里的问题。此外,请随时发布任何建议以改进代码/避免错误。
问候, 小黑子
【问题讨论】:
-
您仍然没有解决您在上一个问题中遇到的分段错误问题。您可能想要解决这个问题,仅仅因为它没有崩溃并不意味着它工作正常。
-
嗨 SoapBox,我相信 Seg 错误是因为没有用值定义大小。我已将其分配给 100。如果还有其他内容,请告诉我。
-
您应该在调用 access 后检查 errno 中的值,以找出它认为它不存在的原因。哦,还要为路径分配一些空间。
-
@darkie15,这不是你的问题。您不能在来自
getcwd()的返回值上调用strcat()。好吧,至少如果您希望您的程序可靠地运行,则不会。 -
请将此标记为作业,除非有其他原因您的文件被命名为
assignment.c?