I have a C
project. I am working in VisualStudio on Ubuntu.
I need to read from a file.
I have this method:
fp = fopen("path_to_file", "r");
if (fp == NULL)
{
printf("\nERROR : file open failed\n");
return 0;
}
while (fgets(buffer, MAX_NAME_LENGTH, (FILE *)fp))
{
printf("%s\n", buffer);
}
fclose(fp);
if (line)
free(line);
My file is located at the root of my project, so my question is - is there a way set way to file like this ${project_root}/my_tmp.txt
?
This way ${project_root}
will be like a general value.
One possible solution would be to utilize the Tasks feature of VSCode and pass the project root path to your compiler as a preprocessor macro using the -D
option, after which you could use it in your sourcecode.
An example (refer here for the complete documentation regarding Tasks) tasks.json
file could look like this. Note the -D
argument in the args
array.
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "default build option",
"command": "/usr/bin/cc",
"args": ["-g", "${file}", "-o", "${fileDirname}/${fileBasenameNoExtension}", "-DPROJECT_ROOT=\"${project_root}\""],
"problemMatcher": ["$gcc"],
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
Then, in your C source, you could utilize the PROJECT_ROOT
macro to construct the filename to open:
fp = fopen(PROJECT_ROOT "/path_to_file", "r");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.