【问题标题】:Issue on file existence in CC中文件存在的问题
【发布时间】: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 ?

标签: c file cygwin


【解决方案1】:

仅仅因为对access() 的调用失败并不意味着该文件不存在。调用可能由于其他原因而失败。

使用printf("error:%s\n", strerror(errno)); 打印出错误消息的文本。

此外,您仍然错误地附加到从 getcwd 收到的“路径”,就像您在上一个问题中一样。即使它没有崩溃,它仍然不正确,可能会给您带来问题……甚至可能是您现在遇到的问题。

getcwd() 为您的路径分配一个缓冲区,但该缓冲区的大小仅适合路径。您正在附加到该缓冲区,超过末尾。这很糟糕,你不能这样做。它会导致问题,并且偶尔会崩溃。你需要停下来了解一下这个 getcwd 函数是如何工作的以及如何正确使用它。

【讨论】:

  • 嗨 SoapBox,我添加了一个新的 char 数组,并使用 strcpy 将现有变量 'path' 存储的值复制到此 char 数组中。现在我已将这个 char 数组用于所有进一步的操作。该代码现在按要求工作。你认为我还有什么需要调查的吗?谢谢你的耐心。问候,小黑
【解决方案2】:

我强烈建议分配足够的空间来存储通过malloc()fpathconf() 的路径(提示,PATH_MAX)。

分配和组装它的非标准方式是asprintf()

确保在不再需要生成路径时释放它,并检查每个可能因用户输入错误而失败的调用是否失败。

如果使用 malloc(),总是检查失败(结果为 NULL)。

祝你任务顺利:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多