这是我的问题:我在字符串矩阵中保存了一些相对路径。根据用户的选择,我必须打开某个文件。问题是,当我使用 fopen 函数时,文件指针没有指向任何东西。这是代码示例:
#include <stdio.h>
#include <stdlib.h>
#define MAX_PATH 100
///Global matrix of strings, containing the paths used in fopen() function
char paths[MAX_PATH][3] = {{"c:\\Users\\ThisPc\\Desktop\\file1.txt"},
{"c:\\Users\\ThisPc\\Desktop\\file2.txt"},
{"c:\\Users\\ThisPc\\Desktop\\file3.txt"}};
int main(){
///Declaring and initializing the 3 file pointers to NULL
FILE *filepntr1 = NULL;
FILE *filepntr2 = NULL;
FILE *filepntr3 = NULL;
///Opening the 3 files with the correct arrays
filepntr1 = fopen(paths[1], "w");
filepntr2 = fopen(paths[2], "w");
filepntr3 = fopen(paths[3], "w");
///Typing something on the files opened, just to check if the files where really opened
fprintf(filepntr1, "hello");
fprintf(filepntr2, "hello");
fprintf(filepntr3, "hello");
///Closing the files
fclose(filepntr1);
fclose(filepntr2);
fclose(filepntr3);
return 0;
}
显然,这三个文件仍然是空白。
我做错了什么?
最佳答案
您错误地创建和填充路径数组的主要问题,例如尝试这种方法:
const char* paths[3] = {"c:\\Users\\ThisPc\\Desktop\\file1.txt",
"c:\\Users\\ThisPc\\Desktop\\file2.txt",
"c:\\Users\\ThisPc\\Desktop\\file3.txt"};
数组索引从0开始的第二期:
filepntr1 = fopen(paths[0], "w");
filepntr2 = fopen(paths[1], "w");
filepntr3 = fopen(paths[2], "w");
关于C - fopen() 的相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31569580/