无法将 char 数组(文件名)传递给 fopen(file,r)

标签 c file path fopen

我希望用户在程序中输入他们想要的文件名,然后程序打开它。我不知道为什么它不起作用,请帮忙。如果我直接在代码上定义路径,它就会起作用。

这有效。

FILE *file;
file = fopen("C:\\Users\\Test\\text.txt", "r");
if (file) {
    index = 0;
    while ((c = getc(file)) != EOF) {
        printf("ok");
    }
    fclose(file);
} else {
    printf("Can't open file");
}

这行不通。

char inputFile[100];

printf("Enter file name: ");
scanf("%s", inputFile);

FILE *file;
file = fopen(inputFile, "r");
if (file) {
    index = 0;
    while ((c = getc(file)) != EOF) {
        printf("ok");
    }
    fclose(file);
} else {
    printf("Can't open file");
}

最佳答案

从代码中读入时,您需要转义“\”,但 scanf 并不那么聪明。您只需按原样输入文本!

C:\Users\Test\text.txt

另外,请注意 scanf ("%s", inputFile) 不会处理文件名路径中的空格,因此“我的文档”将不起作用。

关于无法将 char 数组(文件名)传递给 fopen(file,r),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52305307/

相关文章:

c - omp for 和 omp parallel 的区别

c - beginPacket 上的 UDP 错误

c++ - C/C++ 中有自然数的基本类型吗?

java - 如何在 Java 中将文件路径列表转换为 JSON 对象

Python:具有程序员定义属性的文件

java - 路径中有 Linux JAVA 但权限被拒绝

c - 难以理解递归?

android - 检查 android.graphics.path 与自身的交集

android - 如何永久保存ANDROID_HOME?

android - 在 Android Dropbox API 中递归列出所有文件