Home > Enterprise >  How can I fopen a file in C using Visual Studio?
How can I fopen a file in C using Visual Studio?

Time:06-03

I want to open a file "3.bin" with a C code like below:

//ProgramReport3.c
const char* fileName = "3.bin";
unsigned int data;
unsigned int addr;
unsigned int iCount;    // # of instructions
unsigned int dCount;    // # of data
err = fopen_s(&pFile, fileName, "rb");
printf("%d",err);
if (err) {
    printf("Cannot open file: %s\n", fileName);
    return 1;
}

When I use visual studio code, I just put "3.bin" file in same folder with main.c file: See here

But when I use visual studio, I put ProgramReport3.c file in source folder, and I put 3.bin file in resource file folder but I get below error:

Cannot find 3.bin file

How can I run this code with visual studio??

After I get below comments, I move bin file to same folder where project.exe file is.

(I try to find main.c(in my case ProgramReport3.c)'s exe file I can't find...so I put bin file with project.exe file)

but still it's not working..how can I do next?? Thanks a lot

I put bin file and project.exe file together

CodePudding user response:

For VS, the "3.bin" file needs to be in the same folder as the created executable file - not as the main C-file. This is usually a subfolder of the project folder.

If you do not want to do this manually, you can set the "Copy to Output Directory" property of the file to "Copy Always" in visual studio, so that after the build succeeds, the file is copied to the output directory automatically.

CodePudding user response:

I fix my error! I run code that create file

fp = fopen("test.txt", "w");

and I check above directory (mouse right click -> open folder in file explorer) so I can get position

Thank you for answer!! I helped a lot:) enter image description here

  • Related