UNIX 标准文件编程库概述
UNIX 标准文件编程库提供了一系列函数,用于文件的打开、关闭、读写等操作。这些函数封装了底层的系统调用,提供了更高层次的抽象,方便开发者进行文件操作。无格式读写函数族主要包括字符、行和块级别的读写函数,适用于不同的场景需求。
字符读写函数
字符读写函数用于逐个字符地读写文件,适用于需要精细控制文件内容的场景。常用的字符读写函数包括 fgetc 和 fputc。
字符读取示例:
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("Failed to open file");
return 1;
}
int ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
fclose(file);
return 0;
}
字符写入示例:
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "w");
if (file == NULL) {
perror("Failed to open file");
return 1;
}
char str[] = "Hello, World!";
for (int i = 0; str[i] != '\0'; i++) {
fputc(str[i], file);
}
fclose(file);
return 0;
}
行读写函数
行读写函数用于逐行读写文件,适用于文本文件的处理。常用的行读写函数包括 fgets 和 fputs。
行读取示例:
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("Failed to open file");
return 1;
}
char buffer[256];
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer);
}
fclose(file);
return 0;
}
行写入示例:
#include <stdio.h>
int
5755

被折叠的 条评论
为什么被折叠?



