fopen(), fread(), fwrite(), 和 fclose()来实现。这些函数提供了基本的文本和二进制文件操作功能。clinux文件读写

在Linux系统中,文件读写操作是编程中非常基础且常见的任务,本文将详细介绍如何在C语言中使用系统调用和标准库函数进行文件的打开、读取、写入和关闭操作。
一、打开文件
1. 使用open系统调用
open是一个较低级的系统调用,适用于需要更精细控制的文件操作,它的基本用法如下:
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main() {
int file = open("example.txt", O_RDONLY);
if (file == -1) {
perror("Error opening file");
return 1;
}
// 文件操作...
close(file);
return 0;
}O_RDONLY:以只读方式打开文件。
O_WRONLY:以只写方式打开文件。
O_RDWR:以读写方式打开文件。
O_CREAT:若文件不存在则创建文件。
O_TRUNC:若文件存在,将其长度截为0。
2. 使用fopen标准库函数
fopen提供了更高层次的文件操作接口,更加易用:

#include <stdio.h>
int main() {
FILE* file = fopen("example.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
// 文件操作...
fclose(file);
return 0;
}"r":以只读方式打开文件。
"w":以写入方式打开文件(会清空原有内容)。
"a":以追加方式打开文件。
"r+":以读写方式打开文件。
"w+":以读写方式打开文件(会清空原有内容)。
"a+":以读写方式打开文件(会在文件末尾追加内容)。
1. 使用read系统调用
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#define BUFFER_SIZE 1024
int main() {
int file = open("example.txt", O_RDONLY);
if (file == -1) {
perror("Error opening file");
return 1;
}
char buffer[BUFFER_SIZE];
ssize_t bytesRead;
while ((bytesRead = read(file, buffer, sizeof(buffer))) > 0) {
write(STDOUT_FILENO, buffer, bytesRead); // 输出到标准输出
}
close(file);
return 0;
}2. 使用fread标准库函数
#include <stdio.h>
#define BUFFER_SIZE 1024
int main() {
FILE* file = fopen("example.txt", "r");
if (file == NULL) {
perror("Error opening file");
return 1;
}
char buffer[BUFFER_SIZE];
size_t bytesRead;
while ((bytesRead = fread(buffer, 1, sizeof(buffer), file)) > 0) {
fwrite(buffer, 1, bytesRead, stdout); // 输出到标准输出
}
fclose(file);
return 0;
}fread返回实际读取的元素个数。
1. 使用write系统调用

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main() {
int file = open("example.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (file == -1) {
perror("Error creating file");
return 1;
}
char data[] = "This is some data to be written.";
write(file, data, sizeof(data) 1); // -1是为了不写入字符串的结尾空字符'\0'
close(file);
return 0;
}2. 使用fwrite标准库函数
#include <stdio.h>
int main() {
FILE* file = fopen("example.txt", "w");
if (file == NULL) {
perror("Error creating file");
return 1;
}
char data[] = "This is some data to be written.";
fwrite(data, 1, sizeof(data) 1, file); // -1是为了不写入字符串的结尾空字符'\0'
fclose(file);
return 0;
}fwrite返回实际写入的元素个数。
四、错误处理
在文件操作过程中,错误可能随时发生,因此进行适当的错误处理非常重要,可以使用perror函数打印错误信息:
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int file = open("nonexistent.txt", O_RDONLY);
if (file == -1) {
perror("Error opening file");
return 1;
}
// 文件操作...
close(file);
return 0;
}perror会根据全局变量errno的值输出相应的错误信息。
errno是由系统设置的指示最近一次失败的系统调用的错误码。
常见的错误码包括ENOENT(没有那个文件或目录)、EACCES(权限不够)等。
文件读写是Linux系统编程中必不可少的一部分,本文全面解析了文件读写操作,涵盖了打开文件、读取文件内容、写入文件内容以及错误处理的方方面面,希望本文能帮助读者理解文件读写的基本原理,并能在Linux编程中熟练应用。
小伙伴们,上文介绍了“clinux文件读写”的内容,你了解清楚吗?希望对你有所帮助,任何问题可以给我留言,让我们下期再见吧。
文章来源网络,作者:运维,如若转载,请注明出处:https://shuyeidc.com/wp/44163.html<





