C 文件操作

fread.cpp


#define _CRT_SECURE_NO_WARNINGS


#include <stdio.h>
#include <stdlib.h>
#include <string.h>


typedef struct _Teacher
{
	int age;
	char name[128];
}Teacher;

#define BUFFER 1024
int main()
{
	FILE * fileHandler = fopen("test.txt", "r");
	if (fileHandler == NULL)
	{
		printf("open file error\n");
		return -1;
	}
	Teacher buf[2];
	memset(buf, 0x00, sizeof(buf));

	int len = sizeof(buf) / sizeof(Teacher);
	fread(buf, sizeof(Teacher), len, fileHandler);
	for (int i = 0; i < len; i++)
	{
		printf("Teacher age = %d,name=%s\n", buf[i].age, buf[i].name);
	}
	
	fclose(fileHandler);



	return 0;
}


fwrite.cpp


#define _CRT_SECURE_NO_WARNINGS


#include <stdio.h>
#include <stdlib.h>
#include <string.h>


typedef struct _Teacher
{
	int age;
	char name[128];
}Teacher;

#define BUFFER 1024
int main()
{
	FILE * fileHandler = fopen("test.txt", "w+");
	if (fileHandler == NULL)
	{
		printf("open file error\n");
		return -1;
	}
	Teacher buf[3];
	memset(buf, 0x00, sizeof(buf));
	

	int len = sizeof(buf) / sizeof(buf[0]);
	buf[0].age = 1;
	strcpy(buf[0].name, "abc");

	buf[1].age = 12;
	strcpy(buf[1].name, "abcd");

	buf[2].age = 123;
	strcpy(buf[2].name, "abcde");

	size_t ret = fwrite(buf, sizeof(Teacher),len,fileHandler);
	printf("ret = %d\n", ret);//3
	fclose(fileHandler);



	return 0;
}

fseek

#include <stdio.h>

#define BUFSIZE 6

int main()
{
	FILE *handle = fopen("file.hole", "w+");
	if (handle == NULL)
	{
		printf("fopen failed\n");
		return -1;
	}
	fseek(handle, 1024 * 1024 * 80, SEEK_SET);
	fwrite("\0", 1,1, handle);
	fclose(handle);

	return 0;
}




       char buffer[BUFSIZE];
    memset(buffer, 0, BUFSIZE);
    snprintf(buffer, BUFSIZE - 1, "%s", "hehe");

        memset(buffer, 0, BUFSIZE);
	int maxSize = BUFSIZE - 1;
	int strnlen = maxSize > strlen("hehe") ? strlen("hehe") : maxSize;
	strncpy(buffer, "hehe", strnlen );


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值