Linux系统编程之文件(二)

本文介绍了如何在C语言中使用文件操作函数如fopen、fwrite、fread、fputc和fgetc,分别处理向文件写入结构体数组、字符串以及读取数据。
摘要由CSDN通过智能技术生成

1.向文件中写入结构体

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

struct Test
{
	int a;
	char c;

};

int main()
{
	int fd;
	
	struct Test data[2] = {{100,'a'},{101,'b'}};
	struct Test data2[2];

	fd = open("./file1",O_RDWR);

	int n_write = write(fd,&data,sizeof(struct Test)*2);

	lseek(fd,0,SEEK_SET);

	int n_read = read(fd, &data2, sizeof(struct Test)*2);
	
	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;
}

2.通过C库使用fopen fread fwrite fseek fclose

//FILE *fopen(const char *path, const char *mode);
 


	FILE *fp;
	char *str = "chenlichen hen shuai";
	char readBuf[128] = {0};

	fp = fopen("./chen.txt","w+");

//size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);

//size_t fwrite(const void *ptr, size_t size, size_t nmemb,FILE *stream);
	//ptr  buf
	//size  sizeof char   
	// geshu 
	// which file
	fwrite(str,sizeof(char)*strlen(str),1,fp);
//	fwrite(str,sizeof(char)*strlen(str),1,fp);
	fseek(fp,0,SEEK_SET);

//    size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

//	size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
	fread(readBuf,sizeof(char)*strlen(str),1,fp);
	printf("read data: %s\n",readBuf);

3.用fopen fread fwrite fseek fclose向文件中写一个结构体数组

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
struct Test
{
	int a;
	char c;
}
int main()
{
	FILE *fp;
	struct Test data = {100,'a'};
	struct Test data2;
	fp = fopen("./file1","w+");
	int n_write = fwrite(&data,sizeof(struct Test),1,fp);
	fseek(fp,0,SEEK_SET);
	int n_read = fread(&data2, sizeof(struct Test), 1,fp);
	printf("read %d,%c \n",data2.a,data2.c);
	fclose(fp);
	return 0;
}

4.fputc的使用

	FILE *fp;
	int i;
	char *str = "wang jia hao hen shuai o!";
	int len = strlen(str);

	fp = fopen("./test.txt","w+");
	for(i=0;i<len;i++){

		fputc(*str,fp);
		str++;
	}
	fclose(fp);

5.fgetc的使用

	FILE *fp;
	int i;
	char c;

	fp = fopen("./test.txt","r");

	while(!feof(fp)){// nonezero if reach end of file
		
		c = fgetc(fp);
		printf("%c",c);
	}
	fclose(fp);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

火鸡味の锅巴

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

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

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

打赏作者

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

抵扣说明:

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

余额充值