将相对路径传递给fopen()

Din*_*o55 11 c linux file-io

我试图传递一个相对路径到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)

das*_*ght 8

首先,您需要添加一些空格以path适合array[0]in 的内容strcat,否则您将写入已分配的区域.

其次,你没有传递pathfopen你,因为你"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)


pmg*_*pmg 8

in = fopen("path", " r ");
Run Code Online (Sandbox Code Playgroud)

两个错误就在那里:

  1. 您不希望打开名为"path"的文件,您希望名称在变量中的文件 path
  2. mode参数无效; 你要"r"

为了让他们做对

in = fopen(path, "r");
Run Code Online (Sandbox Code Playgroud)