c - 为什么 C 头文件 stdio.h 中的 fopen 原型(prototype)中有 (const char * ) 参数

标签 c header

我不太明白。我只是一名学生,我注意到 stdio.h 中的一些内容

extern FILE *fopen (const char *__restrict __filename,
                 const char *__restrict __modes)

为什么我们传递“const char *”???,如果我知道这意味着传递指向char类型常量变量的指针。但是像“hello.txt”这样的__filename是字符串类型,而不是字符类型。或者我们这里传递的是这个文件名的地址,但是这个地址是char类型吗???

-- 我也很困惑,这个*是属于__restrict还是__filename,这个__restrict和我们在C99中声明普通C函数时使用的关键字restrict是一样的吗?

--为什么在其他函数原型(prototype)中如

extern int fseek (FILE *__stream, long int __off, int __whence);

传递“long int __off”而不是指针?

最佳答案

传递字符串

why we pass "const char * " ???, if I know this mean pass the pointer to char type constant variable. But __filename like "hello.txt" is strings type, not char type.

C 没有“字符串类型”。在C中,字符串是char的数组。其结尾由空字符(值为零的字符)标记。尽管在诸如 fopen("myfile", "r") 之类的电话中,我们使用"myfile"作为参数,数组 "myfile"自动转换为指向其第一个元素的指针。它的第一个元素是 char ,所以这个指针是 char * .

这来自 C 标准中的一条规则,即 C 2018 6.3.2.1 3,该规则表示任何类型为“array of type”的表达式都会转换为指向其第一个元素的指针,除非:

  • 表达式是 sizeof 的操作数或一元 & ,或
  • 是用于初始化数组的字符串文字(如 char x[] = "abc"; )。

const在参数中

参数的类型为 const char *并不意味着我们必须传递一个指向 const 的指针。 。我们可以将一个普通指针传递给 char ,一个char * ,它会自动转换为 const char * 。这表明该函数将把字符视为 const 。换句话说,该函数只会读取字符;它不会修改它们。

(从技术上讲, const char * 类型的指针可以合法地转换为 char * 并用于修改所指向的对象,只要这些对象最初不是用 const 定义的。但这就是一些东西用于特殊情况。在参数中使用 const 的普通函数定义不会执行此操作。)

__restrict在参数中

-- I also confused, is this * belong to __restrict or __filename, is this __restrict is the same as keyword restrict we use when declare normal C function in C99.

__restrict在某些 C 头文件中使用时表示没有任何意义(针对旧版本的 C 进行编译时)或 restrict (针对现代版本的 C 进行编译时)。例如,在 Apple 与其开发人员工具一起分发的 header 中, <stdio.h>包括定义 __restrict 的 header 这样:

#if __STDC_VERSION__ < 199901
#define __restrict
#else
#define __restrict      restrict
#endif

编译器定义(或省略定义)__STDC_VERSION__根据正在编译的 C 版本(可以使用命令行开关进行选择,例如 -std=c17 )。那么上面的语句定义了 __restrict这样restrict在编译非常旧的 C 版本时不使用,但在编译现代版本时使用。

fseek 的偏移量

Why in other function prototype like ...fseek... pass "long int __off" not pointer?

off参数指定磁盘或其他存储上的文件中的偏移量。它不是主内存中某些内容的地址,因此它不是指针。它是从文件开头算起的字节数,因此它是一个数字。

关于c - 为什么 C 头文件 stdio.h 中的 fopen 原型(prototype)中有 (const char * ) 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58350409/

相关文章:

ios - 如何在 iOS 设备上诊断 dlopen() 中的故障

c - 打印预处理器形成的变量标识符

c - ip4 数据包组装为 ip6 - libnet

html - 标题/导航问题

使用 CSS 类的 PHP header 新页面

css - Phantomjs 不使用自定义样式呈现页脚

Python Popen 输出到 C 程序,fget 在循环中读取相同的 stdin

c - 在 Linux 中从/proc 获取 PID 列表

http - 从 Golang 中的网络/上下文中获取值

php - HTTP header : Expires