在Linux中使用C语言读取文件内容有多种方法,以下是详细的步骤和示例代码。

使用标准I/O库函数
1. fopen、fread、fclose
打开文件:
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("Error opening file");
return EXIT_FAILURE;
} 读取文件:
char buffer[256];
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer);
} 关闭文件:
fclose(file);
2. 完整示例代码
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("Error opening file");
return EXIT_FAILURE;
}
char buffer[256];
while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer);
}
fclose(file);
return 0;
} 使用系统调用
1. open、read、close

打开文件:
int fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("Error opening file");
return EXIT_FAILURE;
} 读取文件:
char buffer[256];
ssize_t bytes_read;
while ((bytes_read = read(fd, buffer, sizeof(buffer) 1)) > 0) {
buffer[bytes_read] = ' ';
printf("%s", buffer);
} 关闭文件:
close(fd);
2. 完整示例代码
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
void readFile() {
int fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("Error opening file");
return;
}
char buffer[256];
ssize_t bytes_read;
while ((bytes_read = read(fd, buffer, sizeof(buffer) 1)) > 0) {
buffer[bytes_read] = ' ';
printf("%s", buffer);
}
close(fd);
}
int main() {
readFile();
return 0;
} 使用内存映射(mmap)
1. mmap、munmap
打开文件并获取文件大小:

int fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("Error opening file");
return EXIT_FAILURE;
}
struct stat fileStat;
fstat(fd, &fileStat); 内存映射文件:
char *mapped = mmap(NULL, fileStat.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (mapped == MAP_FAILED) {
perror("Error mapping file");
close(fd);
return EXIT_FAILURE;
} 读取文件内容:
printf("%s", mapped); 解除映射并关闭文件:
munmap(mapped); close(fd);
2. 完整示例代码
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
void readFileWithMmap() {
int fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("Error opening file");
return;
}
struct stat fileStat;
fstat(fd, &fileStat);
char *mapped = mmap(NULL, fileStat.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
if (mapped == MAP_FAILED) {
perror("Error mapping file");
close(fd);
return;
}
printf("%s", mapped);
munmap(mapped);
close(fd);
}
int main() {
readFileWithMmap();
return 0;
} | 方法 | 优点 | 缺点 | 适用场景 |
| 标准I/O库函数 | 易用性和跨平台特性 | 性能稍低 | 小型文件读写 |
| 系统调用 | 提供更底层的控制 | 需要处理更多细节 | 高性能需求 |
| 内存映射(mmap) | 高效,适合大文件 | 实现复杂 | 大文件快速访问 |
以上就是关于“linux c 读文件内容”的问题,朋友们可以点击主页了解更多内容,希望可以够帮助大家!
本文来源于互联网,如若侵权,请联系管理员删除,本文链接:https://www.9969.net/86843.html