程序无法打开文件,但文件已经存在

时间:2011-01-18 05:58:15

标签: c++ visual-studio-2010 file fopen

我正在编写一个打开图像文件的程序,但奇怪的事情发生了。这是cmd:

的输出
C:\Users\Karl\Pictures>testcvconsole mypic.jpg
argv[0]==testcvconsole
argv[1]==mypic.jpg
fopen is null
strerror(errno)==No such file or directory

当文件在同一目录中的可执行文件旁边时,如果fopen根本无法打开我的文件,我应该考虑一些事情吗?

这是在Windows 7上,Visual Studios Express 2010. C ++。

编辑:以下代码

#include "stdafx.h"
#include <string.h>
#include <errno.h>

int goMain(int argc, char** argv);

int _tmain(int argc, _TCHAR* argv[])
{
 goMain(argc, (char**)argv);
 return 0;
}

int goMain( int argc, char** argv ){

 if (argv[1] != NULL){
  printf("argv[0]==%S\nargv[1]==%S\n", argv[0], argv[1]);

  if (fopen(argv[1], "r") == NULL){
   printf("fopen is null\n");
   printf(strerror(errno));
  }

 }

 return 0;
}

EDIT2

我试过了

char *workingDir =_getcwd(NULL, 0);
printf("workingDir == %S", workingDir);

正如TomK建议的那样,它又回来了:

workingDir ==

什么都没有。嗯...

EDIT3 : 我有所收获。我试过了

argv[1] = "C:/Users/Karl/Pictures/mypic.jpg";

fopen可以打开它。上面的这个陈述是在fopen之前插入的。

4 个答案:

答案 0 :(得分:1)

  1. 可以检查工作目录是否正确吗?

    #include <direct.h>
    
    char *workingDir =_getcwd(NULL, 0);
    
  2. 您可以使用管理员权限运行您的应用程序吗?

答案 1 :(得分:1)

绝对确定他们在同一个目录中。我这样说是因为你使用的是Visual Studio,“同一”目录并不总是那么清楚,因为它取决于你如何通过IDE执行可执行文件。

C:\Users\Karl\Pictures>testcvconsole mypic.jpg

您确定mypic.jpg位于C:\Users\Karl\Pictures吗?

答案 2 :(得分:0)

通常.exe在子目录中创建Debug或Release - 尝试给出图像的绝对路径...

答案 3 :(得分:0)

我遇到了这个问题,结果发现Visual Studio的运行时没有设置当前目录。我从来没有弄清楚问题:相反,我只是使用绝对路径。如果没有绝对路径,您的程序就会查看C:\。您也可以尝试使用".\\mypic.jpg"GetCurrentDirectory()

相关问题