1、使用fgetc()逐字符读取
fgetc() 是 C 标准库中的一个函数,用于从文件流中读取一个字符。它是 stdio.h 头文件中定义的一部分,广泛用于文件处理和输入操作。
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
char ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
fclose(file);
return 0;
}2、使用fgets()逐行读取
fgets()是一个C语言标准库函数,用于从输入流(如文件或网络连接)中读取字符串。从流stream中读取最多n-1个字符到一个字符串s中,并在末尾添加一个NULL字符作为字符串的结束标志。如果读取成功,函数将返回指向字符串的指针;如果遇到文件结束或出错,则返回NULL。
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
char line[256];
while (fgets(line, sizeof(line), file)) {
printf("%s", line);
}
fclose(file);
return 0;
}3、使用fread()块读取
fread() 是一个 C 语言中的函数,它可以从文件流中读取数据。fread() 函数是 C 语言中用于从文件流中读取数据的重要函数。通过合理的使用这个函数,可以轻松实现对文件中数据的读取和处理。在使用过程中,需要注意正确设置参数,并且在读取数据后及时关闭文件流,以避免资源浪费。
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
fseek(file, 0, SEEK_END);
long fileSize = ftell(file);
rewind(file);
char *buffer = (char *)malloc(fileSize + 1);
fread(buffer, 1, fileSize, file);
buffer[fileSize] = '\0';
printf("%s", buffer);
free(buffer);
fclose(file);
return 0;
}
4、使用fscanf()格式化读取
fscanf() 是 C 标准库中的一个函数,用于从文件中读取格式化输入。它是 scanf() 的文件版本,允许从指定的文件流中读取数据并根据提供的格式字符串进行解析。
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
char word[256];
while (fscanf(file, "%s", word) != EOF) {
printf("%s\n", word);
}
fclose(file);
return 0;
}
5、使用低级I/O函数read()逐块读取
C语言中,标准库提供了多种I/O函数,如fread()和fgets(),它们操作方便,但有时我们需要更底层的控制,比如逐块读取文件内容。这时,可以使用UNIX/Linux系统调用中的read()函数。read()函数是一个低级I/O函数,它直接与操作系统交互,提供了对文件描述符的直接访问。
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main() {
int fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("Error opening file");
return 1;
}
char buffer[256];
ssize_t bytesRead;
while ((bytesRead = read(fd, buffer, sizeof(buffer) - 1)) > 0) {
buffer[bytesRead] = '\0';
printf("%s", buffer);
}
close(fd);
return 0;
}