Linux C文件操作函数是指在Linux环境下使用C语言进行文件读写操作的一系列函数。这些函数允许程序打开、读取、写入、关闭文件,以及进行文件的定位和其他管理操作。
open()
:打开文件。close()
:关闭文件。read()
:从文件中读取数据。write()
:向文件中写入数据。lseek()
:改变文件指针的位置。fstat()
:获取文件的状态信息。原因:
解决方法:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
int main() {
int fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("Error opening file");
exit(EXIT_FAILURE);
}
close(fd);
return 0;
}
原因:
解决方法:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("Error opening file");
exit(EXIT_FAILURE);
}
char buffer[1024];
ssize_t bytesRead = read(fd, buffer, sizeof(buffer) - 1);
if (bytesRead == -1) {
perror("Error reading file");
close(fd);
exit(EXIT_FAILURE);
}
buffer[bytesRead] = '\0';
printf("%s\n", buffer);
close(fd);
return 0;
}
原因:
解决方法:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd = open("example.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1) {
perror("Error opening file");
exit(EXIT_FAILURE);
}
const char *data = "Hello, World!";
ssize_t bytesWritten = write(fd, data, strlen(data));
if (bytesWritten == -1) {
perror("Error writing to file");
close(fd);
exit(EXIT_FAILURE);
}
fsync(fd); // Ensure data is written to disk
close(fd);
return 0;
}
希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云