fwrite()与fread()

作者:追风剑情 发布于:2020-4-2 17:07 分类:C

文件读写

示例

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

#define DATA_SIZE  5

int main(int argc, char* argv[])
{
	FILE *fp;
	size_t size;

	/* 写文件 */
	if ((fp = fopen("wordy", "wb+")) == NULL)
	{
		fprintf(stdout, "Can't open \"wordy\" file.\n");
		exit(EXIT_FAILURE);
	}

	int num = 889;
	size = fwrite(&num, sizeof(int), 1, fp);
	printf("fwrite() return: %d\n", size);

	unsigned int *dataPtr = NULL;
	dataPtr = (unsigned int *)malloc(sizeof(int) * DATA_SIZE);
	for (unsigned int i = 0; i < DATA_SIZE; i++)
		dataPtr[i] = i; //初始化

	size = fwrite(dataPtr, sizeof(int), DATA_SIZE, fp);
	printf("fwrite() return: %d\n", size);

	puts("Write Done!");

	/* 读文件 */
	rewind(fp); //回到文件首地址

	size = fread(&num, sizeof(int), 1, fp);
	printf("fread() return: %d\n", size);

	size = fread(dataPtr, sizeof(int), DATA_SIZE, fp);
	printf("fread() return: %d\n", size);

	puts("Read Done!");

	if (fclose(fp) != 0)
		fprintf(stderr, "Error closing file\n");
	free(dataPtr);

	system("pause");
	return 0;
}

运行测试

11111.png

标签: C语言

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号