【问题标题】:How can i declare a file name in c language?如何用c语言声明文件名?
【发布时间】:2013-04-19 14:03:47
【问题描述】:

我有这个 c 模块:

#include "stdafx.h"
#include "targetver.h"

#include "libavutil\mathematics.h"
#include "libavcodec\avcodec.h"

FILE fileName;

我做了文件文件名;

这个我有初始化函数:

void init(const char *filename)
{
    fileName = filename;
    avcodec_register_all();
    printf("Encode video file %s\n", fileName);

所以我做了 fileName = filename; 我这样做的原因是我有另一个名为 start() 的函数:

void start()
{
    /* open it */
    if (avcodec_open2(c, codec, NULL) < 0) {
        fprintf(stderr, "Could not open codec\n");
        exit(1);
    }
//    f = fopen(filename, "wb");
    errn = fopen_s(&f,fileName, "wb");

    if (!f) {
        fprintf(stderr, "Could not open %s\n", fileName);
        exit(1);
    }
}

在开始时我有文件名,但它没有找到它,所以我想改用文件名。 但是我现在遇到了一些错误:

在这一行:fileName = filename;在 = 符号上出现红线错误:

错误 1 ​​错误 C2440: '=' : 无法从 'const char *' 转换为 'FILE'

然后在这一行: errn = fopen_s(&f,fileName, "wb") 在我得到的文件名上:

错误 2 错误 C2065:“文件名”:未声明的标识符

fileName 上这一行的错误号 2 相同:fprintf(stderr, "Could not open %s\n", fileName);

然后fileName = filename上的另一个错误:

6   IntelliSense: no operator "=" matches these operands
        operand types are: FILE = const char *

最后一个错误:7 IntelliSense:不存在从“FILE”到“const char *”的合适转换函数

我想要做的就是声明全局文件名变量以在所有地方使用它。

【问题讨论】:

  • FILE 变量不应该是一个指针吗?
  • 几乎可以肯定是不相关的,但字符串文字中未转义的反斜杠给了我威利。有什么理由不使用 / 而不是 ` \ ` 作为目录分隔符? (适用于我所知道的所有桌面操作系统,包括 Windows。)

标签: c


【解决方案1】:

FILE 是一种类型,用于表示打开的文件(它包含文件句柄、文件中的位置等)。您不能将char * 存储在FILE 类型的变量中,因为它们是不同的类型。 Read about the FILE type here.

您要做的是存储文件名。文件名是一个字符串。请改用const char *。您的错误消息准确地告诉您:“无法将字符串转换为文件”。

Error 1 error C2440: '=' : cannot convert from 'const char *' to 'FILE'

阅读这些错误并尝试理解它们的实际含义可以帮助您解决此类问题。如果编译器抱怨将一种类型转换为另一种类型,这清楚表明您对值的类型或您尝试将其分配给的变量感到困惑。

【讨论】:

    猜你喜欢
    • 2011-09-04
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    相关资源
    最近更新 更多