Program cannot open file, but the file is already there

ぃ、小莉子 提交于 2020-01-06 02:59:06

问题


I am writing a program that will open an image file, but strange thing happened. This is the output from 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

Are there something I should consider when fopen simply failed to open my file when the file is right there along side with the executable file in the same directory?

This is on Windows 7, Visual Studios Express 2010. C++.

EDIT: code below

#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:

I have tried

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

as TomK has suggested and it returned:

workingDir ==

Nothing at all. Hmm...

EDIT3: I am getting something. I tried

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

And fopen can open it. This statement above is inserted right before the fopen.


回答1:


Make absolutely sure they are in the same directory. I'm saying this because you're using Visual Studio, for which the "same" directory isn't always so clear, because it depends on how you execute the executable through the IDE.

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

Are you sure mypic.jpg is located in C:\Users\Karl\Pictures ?




回答2:


  1. Can u check whether the working directory is correct?

    #include <direct.h>
    
    char *workingDir =_getcwd(NULL, 0);
    
  2. Can you run your application with admin privileges?




回答3:


Usually the .exe is created in sub-directory either Debug or Release - try giving the absolute path to the image ...




回答4:


I've had this problem, and it turned out that Visual Studio's runtime wasn't setting the current directory. I never figured out the problem: instead I simply used an absolute path. Without the absolute path, your program is looking in C:\. You can also try using ".\\mypic.jpg" or GetCurrentDirectory().



来源:https://stackoverflow.com/questions/4720936/program-cannot-open-file-but-the-file-is-already-there

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!