在Linux环境下使用C语言进行文件读写操作,主要涉及到标准I/O库中的fopen
、fread
、fwrite
、fclose
等函数,以及低级I/O中的open
、read
、write
、close
等系统调用。
标准I/O库:提供了一组缓冲的文件操作函数,使用起来更方便,适合大多数文件操作场景。
低级I/O系统调用:直接与操作系统内核交互,没有缓冲,适合对性能要求极高或者需要更细粒度控制的场景。
标准I/O库函数:
FILE *fopen(const char *filename, const char *mode)
:打开文件。size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
:从文件中读取数据。size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
:向文件中写入数据。int fclose(FILE *stream)
:关闭文件。低级I/O系统调用:
int open(const char *pathname, int flags)
:打开或创建文件。ssize_t read(int fd, void *buf, size_t count)
:从文件描述符中读取数据。ssize_t write(int fd, const void *buf, size_t count)
:向文件描述符写入数据。int close(int fd)
:关闭文件描述符。标准I/O库示例:
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "w");
if (file == NULL) {
perror("Failed to open file");
return 1;
}
const char *text = "Hello, World!";
fwrite(text, sizeof(char), strlen(text), file);
fclose(file);
return 0;
}
低级I/O系统调用示例:
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main() {
int fd = open("example.txt", O_WRONLY | O_CREAT, 0644);
if (fd == -1) {
perror("Failed to open file");
return 1;
}
const char *text = "Hello, World!";
write(fd, text, strlen(text));
close(fd);
return 0;
}
文件打开失败:
perror
函数打印错误信息。读写错误:
ferror
函数检查标准I/O库的错误状态,或检查系统调用的返回值。文件关闭失败:
在进行文件操作时,还需要注意以下几点:
通过以上方法,可以在Linux环境下使用C语言进行有效的文件读写操作。
领取专属 10元无门槛券
手把手带您无忧上云