我试图传递一个相对路径到fopen(),但它似乎无法找到该文件.我需要这个在Linux上工作.文件名(例如:t1.txt)保存在一个数组中.所以我需要的是相对路径的"前部".
这是我的代码:
// Use strcat to create a relative file path
char path[] = "./textfiles/"; // The "front part" of a relative path
strcat( path, array[0] ); // array[0] = t1.txt
// Open the file
FILE *in;
in = fopen( "path", " r " );
if (!in1)
{
printf("Failed to open text file\n");
exit(1);
}
Run Code Online (Sandbox Code Playgroud)
首先,您需要添加一些空格以path适合array[0]in 的内容strcat,否则您将写入已分配的区域.
其次,你没有传递path给fopen你,因为你"path"用双引号括起来.
char path[100] = "./textfiles/"; // Added some space for array[0]
strcat( path, array[0] );
// Open the file
FILE *in;
in = fopen( path, " r " ); // removed quotes around "path"
if (!in)
{
printf("Failed to open text file\n");
exit(1);
}
Run Code Online (Sandbox Code Playgroud)
in = fopen("path", " r ");
Run Code Online (Sandbox Code Playgroud)
两个错误就在那里:
path"r"为了让他们做对
in = fopen(path, "r");
Run Code Online (Sandbox Code Playgroud)