linux学习:文件系统

目录

例子1   打开文件,并输出是否成功

例子2    打开文件,不存在则创建

例子3   创建一个文件,如果文件已存在,则会失败

例子4   打开文件,写入文本,读取文本并打印出来

例子5   打开、写入、再次打开、读取和关闭操作

例子6    打开、写入、文件指针、读取和关闭操作

例子7    使用 lseek 函数获取该文件的大小

例子8    将一段文本追加到文件末尾

例子9     写入指定的字符串

例子10    清空文件内容,写入字符串

例子11   创建一个新文件

例子12    标准输入读取一定数量字符,写入到标准输出

例子13    文件复制功能

例子14   搜索字符串,修改字符串内容,写回文件

例子15     查找特定标记,并修改紧跟在该标记之后的字符

例子16   一个文件中写入一个整数,然后重新读取这个整数

例子17    向一个文件中写入一个结构体,读取这个结构体

例子18   写入一个结构体数组,读取这些结构体

fopen, fwrite, fread, 和 fseek 函数来操作文件

例子19   写入一个字符串到文件,然后读取

例子20   文件中写入一个字符串,然后重新读取这个字符串

例子21   使用 fwrite 和 fread 函数来写入和读取文件内容大小

例子22   写入一个字符串,读取这个字符串,显示信息字节数

例子23  使用 fwrite 和 fread 写入读取结构体到文件

例子24   fputc将一个字符串逐字符写入到一个文件中

例子25    fgetc从一个文件中逐字符读取内容


例子1   打开文件,并输出是否成功

#include <sys/types.h>  // 包含系统调用所需的基本数据类型
#include <sys/stat.h>   // 包含获取和设置文件属性的功能
#include <fcntl.h>      // 包含文件控制选项,如文件打开函数
#include <stdio.h>      // 包含标准输入输出函数,如printf

int main()
{
	int fd;  // 定义一个整型变量fd,用于存储文件描述符
	
	// 尝试以读写模式打开当前目录下的file1文件,将返回的文件描述符赋值给fd
	fd = open("./file1",O_RDWR);

	// 输出文件描述符的值,如果文件打开成功,显示文件描述符;如果失败,显示-1
	printf("fd = %d\n",fd);

	return 0;  // 程序正常结束,返回0
}

例子2    打开文件,不存在则创建

#include <sys/types.h>  // 包含定义数据类型的系统调用
#include <sys/stat.h>   // 包含定义文件状态的标志
#include <fcntl.h>      // 包含文件控制函数,例如open
#include <stdio.h>      // 包含标准输入输出函数,例如printf

int main()
{
	int fd;  // 定义一个整型变量fd,用于存储文件描述符
	
	// 尝试以读写模式打开当前目录下的file1文件
	fd = open("./file1", O_RDWR);

	if(fd == -1){  // 检查文件是否成功打开,如果返回-1表示打开失败
		printf("open file1 failed\n");  // 打印错误信息

		// 如果文件打开失败,则尝试创建文件,赋予读写权限
		fd = open("./file1", O_RDWR | O_CREAT, 0600);
		
		if(fd > 0){  // 再次检查文件描述符,如果成功创建,则fd应该大于0
			printf("create file1 success!\n");  // 打印文件创建成功的信息
		}
	}

	return 0;  // 程序正常结束
}

例子3   创建一个文件,如果文件已存在,则会失败

#include <sys/types.h>  // 包含定义数据类型的系统调用
#include <sys/stat.h>   // 包含定义文件状态的标志
#include <fcntl.h>      // 包含文件控制定义,如文件访问模式
#include <stdio.h>      // 包含标准输入输出库,例如printf函数

int main()
{
	int fd;  // 定义一个整型变量fd,用于存储文件描述符
	
	// 尝试以读写模式创建一个新文件"./file1",如果该文件已存在,则不创建并返回-1
	fd = open("./file1", O_RDWR | O_CREAT | O_EXCL, 0600);

	if(fd == -1){  // 检查open函数的返回值,如果是-1,则说明文件已经存在或者有其他错误
		printf("file cunZai\n");  // 输出文件已存在的信息
	}

	return 0;  // 程序正常结束,返回0
}

例子4   打开文件,写入文本,读取文本并打印出来

#include <sys/types.h>  // 包含定义数据类型的系统调用
#include <sys/stat.h>   // 包含定义文件状态的标志
#include <fcntl.h>      // 包含文件控制定义,如文件访问模式
#include <stdio.h>      // 包含标准输入输出库,例如printf函数
#include <unistd.h>     // 包含各种常用的系统调用,如read, write, close
#include <string.h>     // 包含字符串处理函数,如strlen
#include <stdlib.h>     // 包含内存分配函数,如malloc和free

int main()
{
	int fd;  // 定义一个整型变量fd,用于存储文件描述符
	char *buf = "helloworld!";	// 定义一个字符串常量

	fd = open("./file1", O_RDWR);  // 尝试以读写模式打开文件file1

	if(fd == -1){  // 检查文件是否成功打开
		printf("open file1 failed\n");  // 打开失败,打印错误消息
		fd = open("./file1", O_RDWR|O_CREAT, 0600);  // 尝试创建文件
		if(fd > 0){  // 检查文件是否成功创建
			printf("create file1 success!\n");  // 创建成功,打印成功消息
		}
	}
	
	printf("open success : fd = %d\n", fd);  // 打印文件描述符,确认文件已打开

	int n_write = write(fd, buf, strlen(buf));  // 向文件写入字符串buf
	if(n_write != -1){  // 检查写入是否成功
		printf("write %d byte to file\n", n_write);  // 打印写入的字节数
	}

	char *readBuf;  // 定义一个字符指针用于读取数据
	readBuf = (char *)malloc(sizeof(char) * n_write + 1);  // 为读取的数据分配内存
	int n_read = read(fd, readBuf, n_write);  // 从文件中读取数据
	
	readBuf[n_read] = '\0';  // 确保字符串正确终止
	printf("read %d bytes, content: %s\n", n_read, readBuf);  // 打印读取的字节数和内容
	close(fd);  // 关闭文件

	return 0;  // 程序结束
}

例子5   打开、写入、再次打开、读取和关闭操作

#include <sys/types.h>  // 包含系统数据类型定义
#include <sys/stat.h>   // 包含文件状态定义
#include <fcntl.h>      // 包含文件控制定义,如文件打开模式
#include <stdio.h>      // 包含标准输入输出函数,如printf
#include <unistd.h>     // 包含POSIX操作系统API,如open、read、write、close
#include <string.h>     // 包含字符串处理函数,如strlen
#include <stdlib.h>     // 包含通用工具库函数,如malloc和free

int main()
{
	int fd;  // 定义一个整型变量fd,用于存储文件描述符
	char *buf = "helloworld!";	// 定义字符串常量buf,用于写入文件

	// 尝试以读写模式打开文件file1
	fd = open("./file1", O_RDWR);

	if(fd == -1){  // 如果文件打开失败(fd为-1)
		printf("open file1 failed\n");  // 输出错误信息
		// 以读写模式创建文件file1,文件权限为0600(仅所有者有读写权限)
		fd = open("./file1", O_RDWR|O_CREAT, 0600);
		if(fd > 0){  // 如果文件创建成功(fd大于0)
			printf("create file1 success!\n");  // 输出创建成功信息
		}
	}
	
	printf("open success : fd = %d\n", fd);  // 输出成功打开文件的文件描述符

	// 向文件写入字符串buf的内容
	int n_write = write(fd, buf, strlen(buf));
	if(n_write != -1){  // 如果写入成功(n_write不为-1)
		printf("write %d bytes to file\n", n_write);  // 输出写入的字节数
	}

	close(fd);  // 关闭文件

	// 再次以读写模式打开文件file1
	fd = open("./file1", O_RDWR);
	char *readBuf;  // 定义字符指针readBuf,用于存储读取的数据
	readBuf = (char *)malloc(sizeof(char) * n_write + 1);  // 为读取的数据分配内存

	// 从文件中读取100字节的数据到readBuf
	int n_read = read(fd, readBuf, 100);
	
	readBuf[n_read] = '\0';  // 确保字符串以null字符结束
	printf("read %d bytes, content: %s\n", n_read, readBuf);  // 输出读取的字节数和内容
	close(fd);  // 关闭文件

	return 0;  // 程序正常结束
}

例子6    打开、写入、文件指针、读取和关闭操作

#include <sys/types.h>  // 包含系统数据类型定义
#include <sys/stat.h>   // 包含文件状态定义
#include <fcntl.h>      // 包含文件控制定义,如文件打开模式
#include <stdio.h>      // 包含标准输入输出函数,如printf
#include <unistd.h>     // 包含POSIX操作系统API,如open、read、write、close,以及lseek
#include <string.h>     // 包含字符串处理函数,如strlen
#include <stdlib.h>     // 包含通用工具库函数,如malloc和free

int main()
{
	int fd;  // 定义一个整型变量fd,用于存储文件描述符
	char *buf = "helloworld!";	// 定义字符串常量buf,用于写入文件

	// 尝试以读写模式打开文件file1
	fd = open("./file1", O_RDWR);

	if(fd == -1){  // 如果文件打开失败(fd为-1)
		printf("open file1 failed\n");  // 输出错误信息
		// 以读写模式创建文件file1,文件权限为0600(仅所有者有读写权限)
		fd = open("./file1", O_RDWR|O_CREAT, 0600);
		if(fd > 0){  // 如果文件创建成功(fd大于0)
			printf("create file1 success!\n");  // 输出创建成功信息
		}
	}
	
	printf("open success : fd = %d\n", fd);  // 输出成功打开文件的文件描述符

	// 向文件写入字符串buf的内容
	int n_write = write(fd, buf, strlen(buf));
	if(n_write != -1){  // 如果写入成功(n_write不为-1)
		printf("write %d bytes to file\n", n_write);  // 输出写入的字节数
	}

	// 分配内存以准备读取文件
	char *readBuf;
	readBuf = (char *)malloc(sizeof(char) * n_write + 1); 

	// 使用lseek移动文件指针,偏移量为-21,即从当前位置(写入结束的地方)向前移动21个字节
	lseek(fd, -21, SEEK_CUR);

	// 从当前文件指针的位置(移动后)开始读取100字节数据到readBuf
	int n_read = read(fd, readBuf, 100);
	
	readBuf[n_read] = '\0';  // 确保字符串以null字符结束
	printf("read %d bytes, content: %s\n", n_read, readBuf);  // 输出读取的字节数和内容
	close(fd);  // 关闭文件

	return 0;  // 程序正常结束
}

例子7    使用 lseek 函数获取该文件的大小

#include <sys/types.h>  // 包含系统数据类型定义
#include <sys/stat.h>   // 包含文件状态定义
#include <fcntl.h>      // 包含文件控制定义,如文件打开模式
#include <stdio.h>      // 包含标准输入输出函数,如printf
#include <unistd.h>     // 包含POSIX操作系统API,如open、close,以及lseek
#include <string.h>     // 包含字符串处理函数,如strlen
#include <stdlib.h>     // 包含通用工具库函数,如malloc和free

int main()
{
	int fd;  // 定义一个整型变量fd,用于存储文件描述符
	char *buf = "helloworld!";	// 定义字符串常量buf,此处未使用

	// 尝试以读写模式打开文件file1
	fd = open("./file1", O_RDWR);

	if (fd == -1) {  // 检查文件是否成功打开
		printf("Unable to open file\n");  // 若文件打开失败,输出错误信息
		return 1;  // 返回错误码1
	}

	// 使用lseek将文件指针移动到文件末尾,返回值是文件指针的位置,即文件的大小
	int filesize = lseek(fd, 0, SEEK_END);
	printf("file's size is: %d bytes\n", filesize);  // 输出文件大小

	close(fd);  // 关闭文件描述符,释放资源

	return 0;  // 程序正常结束
}

例子8    将一段文本追加到文件末尾

#include <sys/types.h>  // 包含系统数据类型定义
#include <sys/stat.h>   // 包含文件状态定义
#include <fcntl.h>      // 包含文件控制定义,如文件打开模式
#include <stdio.h>      // 包含标准输入输出函数,如printf
#include <unistd.h>     // 包含POSIX操作系统API,如open、close,以及write
#include <string.h>     // 包含字符串处理函数,如strlen
#include <stdlib.h>     // 包含通用工具库函数,如malloc和free

int main()
{
	int fd;  // 定义一个整型变量fd,用于存储文件描述符
	char *buf = "helloworld!";	// 定义字符串常量buf,用于追加到文件

	// 尝试以读写模式打开文件file1,并设置O_APPEND标志,确保写入的数据总是追加到文件末尾
	fd = open("./file1", O_RDWR | O_APPEND);

	if(fd == -1) {  // 检查文件是否成功打开
		printf("Unable to open file\n");  // 若文件打开失败,输出错误信息
		return 1;  // 返回错误码1
	}

	printf("open success : fd = %d\n", fd);  // 打印成功打开文件的文件描述符

	// 尝试将buf中的字符串写入打开的文件
	int n_write = write(fd, buf, strlen(buf));
	if(n_write != -1) {  // 检查写入是否成功
		printf("write %d bytes to file\n", n_write);  // 输出写入的字节数
	} else {
		printf("Failed to write to file\n");  // 若写入失败,输出错误信息
	}

	close(fd);  // 关闭文件描述符,释放资源

	return 0;  // 程序正常结束
}

例子9     写入指定的字符串

#include <sys/types.h>  // 包含系统数据类型定义
#include <sys/stat.h>   // 包含文件状态定义
#include <fcntl.h>      // 包含文件控制定义,如文件打开模式
#include <stdio.h>      // 包含标准输入输出函数,如printf
#include <unistd.h>     // 包含POSIX操作系统API,如open、close,以及write
#include <string.h>     // 包含字符串处理函数,如strlen
#include <stdlib.h>     // 包含通用工具库函数,如malloc和free

int main()
{
	int fd;  // 定义一个整型变量fd,用于存储文件描述符
	char *buf = "helloworld!";	// 定义要写入的字符串常量

	// 尝试以读写模式打开文件file1
	fd = open("./file1", O_RDWR);

	if(fd == -1) {  // 检查文件是否成功打开
		printf("Unable to open file\n");  // 若文件打开失败,输出错误信息
		return 1;  // 返回错误码1
	}

	printf("open success : fd = %d\n", fd);  // 打印成功打开文件的文件描述符

	// 尝试将buf中的字符串写入打开的文件
	int n_write = write(fd, buf, strlen(buf));
	if(n_write != -1) {  // 检查写入是否成功
		printf("write %d bytes to file\n", n_write);  // 输出写入的字节数
	} else {
		printf("Failed to write to file\n");  // 若写入失败,输出错误信息
	}

	close(fd);  // 关闭文件描述符,释放资源

	return 0;  // 程序正常结束
}

例子10    清空文件内容,写入字符串

#include <sys/types.h>  // 包含系统数据类型定义
#include <sys/stat.h>   // 包含文件状态定义
#include <fcntl.h>      // 包含文件控制定义,如文件打开模式
#include <stdio.h>      // 包含标准输入输出函数,如printf
#include <unistd.h>     // 包含POSIX操作系统API,如open、close,以及write
#include <string.h>     // 包含字符串处理函数,如strlen
#include <stdlib.h>     // 包含通用工具库函数,如malloc和free

int main()
{
	int fd;  // 定义一个整型变量fd,用于存储文件描述符
	char *buf = "test";  // 定义要写入的字符串常量

	// 尝试以读写模式打开文件file1,如果文件已存在,则将其长度截为0(清空文件)
	fd = open("./file1", O_RDWR | O_TRUNC);

	if(fd == -1) {  // 检查文件是否成功打开
		printf("Unable to open file\n");  // 若文件打开失败,输出错误信息
		return 1;  // 返回错误码1
	}

	printf("open success : fd = %d\n", fd);  // 打印成功打开文件的文件描述符

	// 尝试将buf中的字符串写入打开的文件
	int n_write = write(fd, buf, strlen(buf));
	if(n_write != -1) {  // 检查写入是否成功
		printf("write %d bytes to file\n", n_write);  // 输出写入的字节数
	} else {
		printf("Failed to write to file\n");  // 若写入失败,输出错误信息
	}

	close(fd);  // 关闭文件描述符,释放资源

	return 0;  // 程序正常结束
}

例子11   创建一个新文件

#include <sys/types.h>  // 包含系统数据类型定义
#include <sys/stat.h>   // 包含文件状态定义,例如mode_t
#include <fcntl.h>      // 包含文件控制定义,例如文件打开模式
#include <stdio.h>      // 包含标准输入输出函数
#include <unistd.h>     // 包含POSIX操作系统API
#include <string.h>     // 包含字符串处理函数
#include <stdlib.h>     // 包含标准库函数

int main()
{
	int fd;  // 文件描述符,用于存储creat函数的返回值

	// 创建一个新文件,位于路径"/home/CLC/file1"
	// S_IRWXU是文件权限标志,它设置文件拥有者具有读、写和执行权限
	fd = creat("file1", S_IRWXU);

	if (fd == -1) {  // 检查文件是否成功创建
		perror("Failed to create file");  // 使用perror输出错误原因
		return 1;  // 返回错误码1,表示出现错误
	}

	close(fd);  // 成功创建文件后,关闭文件描述符
	return 0;  // 程序正常结束
}

例子12    标准输入读取一定数量字符,写入到标准输出

#include <sys/types.h>  // 包含系统数据类型定义
#include <sys/stat.h>   // 包含文件状态定义
#include <fcntl.h>      // 包含文件控制定义
#include <stdio.h>      // 包含标准输入输出函数,如printf
#include <unistd.h>     // 包含POSIX操作系统API,如read和write
#include <string.h>     // 包含字符串处理函数,如strlen
#include <stdlib.h>     // 包含标准库函数

int main()
{

	char readBuf[128];  // 创建一个字符数组,用于存储从标准输入读取的数据

	// 从标准输入(文件描述符0)读取最多5个字节的数据到readBuf中
	int n_read = read(0, readBuf, 5);

	// 将读取的字符串(readBuf)写入到标准输出(文件描述符1)
	// strlen(readBuf)可能不准确,因为read不会在字符串末尾添加'\0'
	int n_write = write(1, readBuf, strlen(readBuf));

	// 输出换行符和完成消息
	printf("\ndone!\n");
	return 0;  // 程序正常结束
}

例子13    文件复制功能

#include <sys/types.h>  // 包含系统数据类型定义
#include <sys/stat.h>   // 包含文件状态定义
#include <fcntl.h>      // 包含文件控制定义,如文件打开模式
#include <stdio.h>      // 包含标准输入输出函数,如printf
#include <unistd.h>     // 包含POSIX操作系统API,如open、close、read、write,及lseek
#include <string.h>     // 包含字符串处理函数,如strlen
#include <stdlib.h>     // 包含通用工具库函数,如malloc、free和exit

int main(int argc, char **argv)
{
	int fdSrc, fdDes;  // 定义两个文件描述符,分别用于源文件和目标文件

	char *readBuf = NULL;  // 定义字符指针,用于存储读取的文件内容

	if(argc != 3){  // 检查命令行参数数量是否正确
		printf("parameter error\n");  // 如果参数不正确,输出错误信息
		exit(-1);  // 非正常退出程序
	}

	// 打开源文件,文件模式为读写
	fdSrc = open(argv[1], O_RDWR);
	if (fdSrc == -1) {  // 检查文件是否成功打开
		perror("Failed to open source file");
		exit(-1);
	}

	// 使用lseek获取文件大小
	int size = lseek(fdSrc, 0, SEEK_END);
	// 将文件指针重置到文件开始处
	lseek(fdSrc, 0, SEEK_SET);

	// 根据文件大小动态分配内存,加8是为了额外空间,防止溢出
	readBuf = (char *)malloc(sizeof(char) * size + 8);
	if (readBuf == NULL) {  // 检查内存分配是否成功
		perror("Memory allocation failed");
		close(fdSrc);
		exit(-1);
	}

	// 从源文件中读取全部数据到内存
	int n_read = read(fdSrc, readBuf, size);
	if (n_read == -1) {  // 检查读取是否成功
		perror("Failed to read source file");
		free(readBuf);
		close(fdSrc);
		exit(-1);
	}

	// 打开目标文件,文件模式为读写,如果文件不存在则创建,如果文件存在则截断为0
	fdDes = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, 0600);
	if (fdDes == -1) {  // 检查文件是否成功打开
		perror("Failed to open destination file");
		free(readBuf);
		close(fdSrc);
		exit(-1);
	}

	// 将读取的数据写入目标文件
	int n_write = write(fdDes, readBuf, strlen(readBuf));
	if (n_write == -1) {  // 检查写入是否成功
		perror("Failed to write to destination file");
	}

	// 关闭两个文件描述符
	close(fdSrc);
	close(fdDes);
	// 释放动态分配的内存
	free(readBuf);

	return 0;  // 程序正常结束
}

例子14   搜索字符串,修改字符串内容,写回文件

#include <sys/types.h>  // 包含系统数据类型定义
#include <sys/stat.h>   // 包含文件状态定义
#include <fcntl.h>      // 包含文件控制定义,如文件打开模式
#include <stdio.h>      // 包含标准输入输出函数,如printf
#include <unistd.h>     // 包含POSIX操作系统API,如open、close、read、write,及lseek
#include <string.h>     // 包含字符串处理函数,如strstr和strlen
#include <stdlib.h>     // 包含通用工具库函数,如malloc、free和exit

int main(int argc, char **argv)
{
	int fdSrc;  // 文件描述符,用于源文件

	char *readBuf = NULL;  // 指针,用于存储读取的文件内容

	if(argc != 2){  // 检查命令行参数数量是否正确
		printf("parameter error\n");  // 如果参数不正确,输出错误信息
		exit(-1);  // 非正常退出程序
	}

	// 打开源文件,文件模式为读写
	fdSrc = open(argv[1], O_RDWR);
	if (fdSrc == -1) {  // 检查文件是否成功打开
		perror("Failed to open source file");
		exit(-1);
	}

	// 使用lseek获取文件大小
	int size = lseek(fdSrc, 0, SEEK_END);
	// 将文件指针重置到文件开始处
	lseek(fdSrc, 0, SEEK_SET);

	// 根据文件大小动态分配内存,加8是为了额外空间,防止溢出
	readBuf = (char *)malloc(sizeof(char) * size + 8);
	if (readBuf == NULL) {  // 检查内存分配是否成功
		perror("Memory allocation failed");
		close(fdSrc);
		exit(-1);
	}

	// 从源文件中读取全部数据到内存
	int n_read = read(fdSrc, readBuf, size);
	if (n_read == -1) {  // 检查读取是否成功
		perror("Failed to read source file");
		free(readBuf);
		close(fdSrc);
		exit(-1);
	}

	// 使用strstr查找字符串"LENG=",返回第一次出现的位置
	char *p = strstr(readBuf, "LENG=");
	if(p == NULL){  // 如果没有找到字符串
		printf("not found\n");
		free(readBuf);
		close(fdSrc);
		exit(-1);
	}
	
	// 移动指针到"LENG="后的第一个字符
	p += strlen("LENG=");
	// 修改找到的位置的字符为'5'
	*p = '5';
	
	// 将文件指针重置到文件开始处
	lseek(fdSrc, 0, SEEK_SET);
	// 将修改后的内容写回文件
	int n_write = write(fdSrc, readBuf, strlen(readBuf));
	if (n_write == -1) {  // 检查写入是否成功
		perror("Failed to write to source file");
	}

	// 关闭文件描述符
	close(fdSrc);
	// 释放动态分配的内存
	free(readBuf);

	return 0;  // 程序正常结束
}

例子15     查找特定标记,并修改紧跟在该标记之后的字符

#include <sys/types.h>  // 包含系统数据类型定义
#include <sys/stat.h>   // 包含文件状态定义
#include <fcntl.h>      // 包含文件控制定义,如文件打开模式
#include <stdio.h>      // 包含标准输入输出函数,如printf
#include <unistd.h>     // 包含POSIX操作系统API,如open、close、read、write,及lseek
#include <string.h>     // 包含字符串处理函数,如strstr和strlen
#include <stdlib.h>     // 包含通用工具库函数,如malloc、free和exit

int main(int argc, char **argv)
{
	int fdSrc;  // 文件描述符,用于源文件

	char *readBuf = NULL;  // 指针,用于存储读取的文件内容

	if(argc != 2){  // 检查命令行参数数量是否正确
		printf("parameter error\n");  // 如果参数不正确,输出错误信息
		exit(-1);  // 非正常退出程序
	}

	// 打开源文件,文件模式为读写
	fdSrc = open(argv[1], O_RDWR);
	if (fdSrc == -1) {  // 检查文件是否成功打开
		perror("Failed to open source file");
		exit(-1);
	}

	// 使用lseek获取文件大小
	int size = lseek(fdSrc, 0, SEEK_END);
	// 将文件指针重置到文件开始处
	lseek(fdSrc, 0, SEEK_SET);

	// 根据文件大小动态分配内存,加8是为了额外空间,防止溢出
	readBuf = (char *)malloc(sizeof(char) * size + 8);
	if (readBuf == NULL) {  // 检查内存分配是否成功
		perror("Memory allocation failed");
		close(fdSrc);
		exit(-1);
	}

	// 从源文件中读取全部数据到内存
	int n_read = read(fdSrc, readBuf, size);
	if (n_read == -1) {  // 检查读取是否成功
		perror("Failed to read source file");
		free(readBuf);
		close(fdSrc);
		exit(-1);
	}

	// 使用strstr查找字符串"LENG=",返回第一次出现的位置
	char *p = strstr(readBuf, "LENG=");
	if(p == NULL){  // 如果没有找到字符串
		printf("not found\n");
		free(readBuf);
		close(fdSrc);
		exit(-1);
	}
	
	// 移动指针到"LENG="后的第一个字符
	p += strlen("LENG=");
	// 修改找到的位置的字符为数值5
	*p = 5;
	
	// 将文件指针重置到文件开始处
	lseek(fdSrc, 0, SEEK_SET);
	// 将修改后的内容写回文件
	int n_write = write(fdSrc, readBuf, strlen(readBuf));
	if (n_write == -1) {  // 检查写入是否成功
		perror("Failed to write to source file");
	}

	// 关闭文件描述符
	close(fdSrc);
	// 释放动态分配的内存
	free(readBuf);

	return 0;  // 程序正常结束
}

例子16   一个文件中写入一个整数,然后重新读取这个整数

#include <sys/types.h>  // 包含系统数据类型定义
#include <sys/stat.h>   // 包含文件状态定义
#include <fcntl.h>      // 包含文件控制定义,如文件打开模式
#include <stdio.h>      // 包含标准输入输出函数,如printf
#include <unistd.h>     // 包含POSIX操作系统API,如open、close、read、write,及lseek
#include <string.h>     // 包含字符串处理函数
#include <stdlib.h>     // 包含通用工具库函数

int main()
{
	int fd;  // 文件描述符,用于源文件

	int data = 100;  // 定义并初始化一个整数data为100
	int data2 = 0;   // 定义另一个整数data2用于接收从文件读取的数据

	// 打开名为"./file1"的文件,文件模式为读写
	fd = open("./file1", O_RDWR);
	if (fd == -1) {  // 检查文件是否成功打开
		perror("Failed to open file");
		exit(-1);
	}

	// 向文件写入整数data
	int n_write = write(fd, &data, sizeof(int));
	if (n_write != sizeof(int)) {  // 检查是否成功写入了整个int
		perror("Failed to write complete data");
		close(fd);
		exit(-1);
	}

	// 将文件指针重置到文件开始处
	lseek(fd, 0, SEEK_SET);

	// 从文件中读取整数到data2
	int n_read = read(fd, &data2, sizeof(int));
	if (n_read != sizeof(int)) {  // 检查是否成功读取了整个int
		perror("Failed to read data");
		close(fd);
		exit(-1);
	}
	
	// 打印读取的数据
	printf("read %d \n", data2);

	// 关闭文件描述符
	close(fd);

	return 0;  // 程序正常结束
}

例子17    向一个文件中写入一个结构体,读取这个结构体

#include <sys/types.h>  // 包含系统数据类型定义
#include <sys/stat.h>   // 包含文件状态定义
#include <fcntl.h>      // 包含文件控制定义,如文件打开模式
#include <stdio.h>      // 包含标准输入输出函数,如printf
#include <unistd.h>     // 包含POSIX操作系统API,如open、close、read、write,及lseek
#include <string.h>     // 包含字符串处理函数
#include <stdlib.h>     // 包含通用工具库函数

// 定义一个结构体Test,包含一个整数a和一个字符c
struct Test
{
	int a;
	char c;
};

int main()
{
	int fd;  // 文件描述符,用于源文件

	struct Test data = {100, 'a'};  // 创建并初始化结构体data
	struct Test data2;  // 创建另一个结构体data2用于接收从文件读取的数据

	// 打开名为"./file1"的文件,文件模式为读写
	fd = open("./file1", O_RDWR);
	if (fd == -1) {  // 检查文件是否成功打开
		perror("Failed to open file");
		exit(-1);
	}

	// 向文件写入结构体data
	int n_write = write(fd, &data, sizeof(struct Test));
	if (n_write != sizeof(struct Test)) {  // 检查是否成功写入了整个结构体
		perror("Failed to write complete data");
		close(fd);
		exit(-1);
	}

	// 将文件指针重置到文件开始处
	lseek(fd, 0, SEEK_SET);

	// 从文件中读取结构体到data2
	int n_read = read(fd, &data2, sizeof(struct Test));
	if (n_read != sizeof(struct Test)) {  // 检查是否成功读取了整个结构体
		perror("Failed to read data");
		close(fd);
		exit(-1);
	}
	
	// 打印读取的数据,显示结构体data2中的整数和字符
	printf("read %d,%c \n", data2.a, data2.c);

	// 关闭文件描述符
	close(fd);

	return 0;  // 程序正常结束
}

例子18   写入一个结构体数组,读取这些结构体

#include <sys/types.h>  // 包含系统数据类型定义
#include <sys/stat.h>   // 包含文件状态定义
#include <fcntl.h>      // 包含文件控制定义,如文件打开模式
#include <stdio.h>      // 包含标准输入输出函数,如printf
#include <unistd.h>     // 包含POSIX操作系统API,如open、close、read、write,及lseek
#include <string.h>     // 包含字符串处理函数
#include <stdlib.h>     // 包含通用工具库函数

// 定义一个结构体Test,包含一个整数a和一个字符c
struct Test
{
	int a;
	char c;
};

int main()
{
	int fd;  // 文件描述符,用于源文件

	// 创建并初始化结构体数组data,包含两个元素
	struct Test data[2] = {{100, 'a'}, {101, 'b'}};
	struct Test data2[2];  // 创建另一个结构体数组data2用于接收从文件读取的数据

	// 打开名为"./file1"的文件,文件模式为读写
	fd = open("./file1", O_RDWR);
	if (fd == -1) {  // 检查文件是否成功打开
		perror("Failed to open file");
		exit(-1);
	}

	// 向文件写入结构体数组data
	int n_write = write(fd, &data, sizeof(struct Test) * 2);
	if (n_write != sizeof(struct Test) * 2) {  // 检查是否成功写入了整个数组
		perror("Failed to write complete data");
		close(fd);
		exit(-1);
	}

	// 将文件指针重置到文件开始处
	lseek(fd, 0, SEEK_SET);

	// 从文件中读取结构体数组到data2
	int n_read = read(fd, &data2, sizeof(struct Test) * 2);
	if (n_read != sizeof(struct Test) * 2) {  // 检查是否成功读取了整个数组
		perror("Failed to read data");
		close(fd);
		exit(-1);
	}
	
	// 打印读取的数据,显示数组中每个元素的整数和字符
	printf("read %d,%c \n", data2[0].a, data2[0].c);
	printf("read %d,%c \n", data2[1].a, data2[1].c);

	// 关闭文件描述符
	close(fd);

	return 0;  // 程序正常结束
}

fopen, fwrite, fread, 和 fseek 函数来操作文件

例子19   写入一个字符串到文件,然后读取

#include <stdio.h>  // 包含标准输入输出函数库
#include <string.h> // 包含字符串处理函数库

int main()
{
	FILE *fp;  // 文件指针,用于操作文件
	char *str = "helloworld";  // 要写入文件的字符串
	char readBuf[128] = {0};  // 读缓冲区,初始化为0

	// 使用"w+"模式打开文件,该模式支持读写操作,如果文件不存在则创建,如果存在则清空
	fp = fopen("./text.txt", "w+");
	if (fp == NULL) {  // 检查文件是否成功打开
		perror("Failed to open file");
		return -1;
	}

	// 将字符串写入文件,每个元素大小为sizeof(char),元素个数为strlen(str),写入文件fp
	fwrite(str, sizeof(char), strlen(str), fp);

	// 重新定位文件指针到文件的开始,准备读取内容
	fseek(fp, 0, SEEK_SET);

	// 从文件中读取数据到readBuf,每个元素大小为sizeof(char),要读取的元素个数为strlen(str)
	fread(readBuf, sizeof(char), strlen(str), fp);
	
	// 输出读取到的数据
	printf("read data: %s\n", readBuf);

	// 关闭文件
	fclose(fp);

	return 0;  // 程序正常结束
}

例子20   文件中写入一个字符串,然后重新读取这个字符串

#include <stdio.h>  // 包含标准输入输出函数库
#include <string.h> // 包含字符串处理函数库

int main()
{
    FILE *fp;  // 定义一个FILE类型的指针,用于操作文件
    char *str = "helloworld";  // 定义一个字符串,用于写入文件
    char readBuf[128] = {0};  // 定义一个读缓冲区,并初始化所有元素为0

    // 以读写模式打开一个名为"text.txt"的文件,如果文件不存在则创建,如果存在则清空内容
    fp = fopen("./text.txt", "w+");
    if (fp == NULL) {  // 检查文件是否成功打开
        perror("Failed to open file");
        return -1;
    }

    // 将字符串str写入文件,写入长度为strlen(str)*sizeof(char),即字符串的长度,单位是字节数
    fwrite(str, sizeof(char) * strlen(str), 1, fp);

    // 将文件内的位置指针重置到文件的开始
    fseek(fp, 0, SEEK_SET);

    // 从文件中读取数据到readBuf,读取的长度和写入长度一样
    fread(readBuf, sizeof(char) * strlen(str), 1, fp);

    // 打印读取到的数据
    printf("read data: %s\n", readBuf);

    // 关闭文件
    fclose(fp);

    return 0;  // 程序正常结束
}

例子21   使用 fwritefread 函数来写入和读取文件内容大小

#include <stdio.h>  // 包含标准输入输出函数库
#include <string.h> // 包含字符串处理函数库

int main()
{
    FILE *fp;  // 定义一个FILE类型的指针,用于文件操作
    char *str = "helloworld";  // 要写入文件的字符串
    char readBuf[128] = {0};  // 定义一个读缓冲区,并初始化所有元素为0

    // 以读写模式打开一个名为"chen.txt"的文件,如果文件不存在则创建,如果存在则清空内容
    fp = fopen("./text.txt", "w+");
    if (fp == NULL) {  // 检查文件是否成功打开
        perror("Failed to open file");
        return -1;
    }

    // 尝试写入100个字符大小的数据,但实际上str长度小于100,因此会写入实际字符串长度加上未定义内容直到100字符
    int nwrite = fwrite(str, sizeof(char), 100, fp);

    // 重置文件指针到文件开头,以便从头开始读取文件
    fseek(fp, 0, SEEK_SET);

    // 从文件中读取与原始字符串长度相同的数据到readBuf
    int nread = fread(readBuf, sizeof(char), strlen(str), fp);

    // 输出读取到的数据
    printf("read data: %s\n", readBuf);
    printf("read=%d, write=%d\n", nread, nwrite);  // 打印实际读写的字符数

    // 关闭文件
    fclose(fp);

    return 0;  // 程序正常结束
}

例子22   写入一个字符串,读取这个字符串,显示信息字节数

#include <stdio.h>  // 包含标准输入输出函数库
#include <string.h> // 包含字符串处理函数库

int main()
{
    FILE *fp;  // 定义一个FILE类型的指针,用于操作文件
    char *str = "chenlichen hen shuai";  // 定义一个字符串,用于写入文件
    char readBuf[128] = {0};  // 定义一个读缓冲区,并初始化所有元素为0

    // 以读写模式打开一个名为"chen.txt"的文件,如果文件不存在则创建,如果存在则清空内容
    fp = fopen("./chen.txt", "w+");
    if (fp == NULL) {  // 检查文件是否成功打开
        perror("Failed to open file");
        return -1;
    }

    // 将字符串str写入文件,使用sizeof(char)*strlen(str)计算需要写入的总字节数,写入1个这样的单位
    int nwrite = fwrite(str, sizeof(char) * strlen(str), 1, fp);
    // 重置文件指针到文件开头,以便从头开始读取文件
    fseek(fp, 0, SEEK_SET);

    // 从文件中读取数据到readBuf,读取长度为strlen(str)个字符,尝试读取100个这样的单位
    int nread = fread(readBuf, sizeof(char) * strlen(str), 100, fp);

    // 输出读取到的数据
    printf("read data: %s\n", readBuf);
    // 打印实际读写的字节数
    printf("read=%d, write=%d\n", nread, nwrite);

    // 关闭文件
    fclose(fp);

    return 0;  // 程序正常结束
}

例子23  使用 fwritefread 写入读取结构体到文件

#include <sys/types.h>  // 包含系统数据类型定义
#include <sys/stat.h>   // 包含文件状态定义
#include <fcntl.h>      // 包含文件控制定义
#include <stdio.h>      // 包含标准输入输出函数库
#include <unistd.h>     // 包含POSIX操作系统API,如close
#include <string.h>     // 包含字符串处理函数
#include <stdlib.h>     // 包含标准库函数,如exit

// 定义一个结构体Test,包含一个整数和一个字符
struct Test
{
	int a;
	char c;
};

int main()
{
	FILE *fp;  // 定义一个FILE类型的指针,用于文件操作
	struct Test data = {100, 'a'};  // 创建并初始化结构体data
	struct Test data2;  // 创建另一个结构体data2用于接收从文件读取的数据

	// 以读写模式打开一个名为"file1"的文件,如果文件不存在则创建,如果存在则清空内容
	fp = fopen("./file1", "w+");
	if (fp == NULL) {  // 检查文件是否成功打开
		perror("Failed to open file");
		return -1;
	}

	// 将结构体data写入文件
	int n_write = fwrite(&data, sizeof(struct Test), 1, fp);
	if (n_write != 1) {  // 检查是否成功写入一个结构体
		perror("Failed to write data");
		fclose(fp);
		return -1;
	}

	// 将文件内的位置指针重置到文件的开始
	fseek(fp, 0, SEEK_SET);

	// 从文件中读取结构体到data2
	int n_read = fread(&data2, sizeof(struct Test), 1, fp);
	if (n_read != 1) {  // 检查是否成功读取一个结构体
		perror("Failed to read data");
		fclose(fp);
		return -1;
	}
	
	// 打印读取的数据,显示结构体data2中的整数和字符
	printf("read %d,%c \n", data2.a, data2.c);

	// 关闭文件
	fclose(fp);

	return 0;  // 程序正常结束
}

例子24   fputc将一个字符串逐字符写入到一个文件中

#include <stdio.h>  // 包含标准输入输出函数库
#include <string.h> // 包含字符串处理函数库

int main()
{
    FILE *fp;  // 定义一个FILE类型的指针,用于文件操作
    int i;  // 循环控制变量
    char *str = "helloworld!";  // 定义并初始化一个字符串
    int len = strlen(str);  // 计算字符串的长度

    // 以读写模式打开一个名为"test.txt"的文件,如果文件不存在则创建,如果存在则清空内容
    fp = fopen("./test.txt", "w+");
    if (fp == NULL) {  // 检查文件是否成功打开
        perror("Failed to open file");
        return -1;
    }

    // 循环遍历字符串中的每一个字符
    for(i = 0; i < len; i++) {
        // 写入当前字符到文件中,*str是指向当前字符的指针
        fputc(*str, fp);
        // 指针后移,指向下一个字符
        str++;
    }

    // 关闭文件
    fclose(fp);

    return 0;  // 程序正常结束
}

例子25    fgetc从一个文件中逐字符读取内容

#include <stdio.h>  // 包含标准输入输出函数库
#include <string.h> // 包含字符串处理函数库

int main()
{
    FILE *fp;  // 定义一个FILE类型的指针,用于文件操作
    int i;     // 未使用的变量,可以移除
    char c;    // 用于存储从文件读取的每个字符

    // 以只读模式打开一个名为"test.txt"的文件
    fp = fopen("./test.txt", "r");
    if (fp == NULL) {  // 检查文件是否成功打开
        perror("Failed to open file");
        return -1;
    }

    // 使用feof(fp)来检测文件结束,当未到达文件末尾时,循环继续
    while(!feof(fp)) {  // 如果没有达到文件末尾
        c = fgetc(fp);  // 从文件中读取一个字符
        
        // 在未检测到文件结束前,最后一次循环可能读取到EOF
        if (feof(fp)) { 
            break;  // 如果读取到文件结束,跳出循环
        }
        
        printf("%c", c);  // 打印读取的字符
    }

    // 关闭文件
    fclose(fp);

    return 0;  // 程序正常结束
}

  • 15
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值