D
D
dandropov952018-08-29 23:20:25
C++ / C#
dandropov95, 2018-08-29 23:20:25

In what directory should the file be stored for reading from the program?

Tell me in which directory to put the file for reading, regarding the project (VS) so that the file can be opened along the path "file_name.ext"?
I have already tried to put in all the folders created by the studio, but the file still does not open.
fopen("file.txt", "r")
But if you specify an absolute path (for example, to drive C), then everything works.
fopen("c:\\file.txt", "r")

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman, 2018-08-30
@myjcom

С:\\Projects\\myProject\\Debug\\file.txt    == ..\\debug\\file.txt
С:\\Projects\\myProject\\Release\\file.txt  == ..\\release\\file.txt
С:\\Projects\\myProject\\Other\\file.txt    == ..\\other\\file.txt
С:\\Projects\\myProject\\file.txt           == ..\\file.txt
...
fopen("..\\file.txt", "r")

spoiler
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <direct.h>

char* get_file_path(char* dir, char* fname)
{
    dir = _getcwd(dir, MAX_PATH);
    strcpy(&dir[strlen(dir)], "\\");
    strcpy(&dir[strlen(dir)], fname);
    return dir;
}

int main(int argc, char* argv[])
{
    /* uncomment
    if(argc != 1)
    {
        printf("error: usage myapp.exe file.txt\n");
        return -1;
    }
    uncomment */
    char  dir[MAX_PATH];
    char* file = "file.txt";//test
    char* full_file_name = get_file_path(dir, file);// get_file_path(dir, argv[0])
    FILE* fp = fopen(full_file_name, "r");

    if(fp)
    {
        printf("Open\n");
        fclose(fp);
    }

    printf("%s", full_file_name);
    free(full_file_name);
    return 0;
}

R
res2001, 2018-08-30
@res2001

Pass the path to the file as a parameter and put it anywhere.

C
CityCat4, 2018-08-30
@CityCat4

Without specifying a path, the program assumes that the file is in the directory that is currently current for it. And this is not always the directory that you mean :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question