C - fopen() 的相对路径

标签 c arrays file io fopen

这是我的问题:我在字符串矩阵中保存了一些相对路径。根据用户的选择,我必须打开某个文件。问题是,当我使用 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/

相关文章:

java - Java File 实例存储在哪里?

c# - 读取文件时出现 UnauthorizedAccessException

C程序 将 float 转换为字母等级

c - 如何用 C 语言读取文件的特定部分?

javascript - 将对象数组转换为键值对对象

javascript - 从数组中删除重复项的最简单方法,同时仍保留最后一个

c - 变量 FILE * 的声明(静态或非静态)

c - TTF_OpenFont 第 N 次尝试失败

javascript - 返回的数组打印数组索引而不是值

iphone - NSFileManager 在应用程序委托(delegate)中崩溃