⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ho21_5.c

📁 Software Development in C: A Practical Approach to Programming and Design 软件开发:编程与设计(C))——国外经典教材·计
💻 C
字号:
#include <stdio.h>

#define MAX_STRING_LENGTH 256
#define STATE_NAME_LENGTH 3


typedef enum
{
	NO_ERROR = 0,
	CANT_OPEN_FILE,
	FILE_IO_ERROR
} error_status;

typedef struct
{
	char name[MAX_STRING_LENGTH];
	char streetAddress1[MAX_STRING_LENGTH];
	char streetAddress2[MAX_STRING_LENGTH];
	char city[MAX_STRING_LENGTH];
	char state[STATE_NAME_LENGTH];
	unsigned zip;
} customer;


int main()
{
	error_status errorStatus = NO_ERROR;


	customer aCustomer = {"Bill Williams",
						  "1234 5th St",
						  "Apt. #24",
						  "Big City",
						  "NM",
						  87654};
	FILE *fp = NULL;
	
	fp=fopen("data.bin","wb");
	if (!fp)
	{
		printf("Could not open file\n");
		errorStatus = CANT_OPEN_FILE;
	}
	else
	{
		if (fwrite((void *)(&aCustomer),sizeof(customer),1,fp) != 1)
		{
			errorStatus = FILE_IO_ERROR;
		}
		else
		{
			fclose(fp);
		}
	}

	if (errorStatus == NO_ERROR)
	{
		fp = fopen("data.bin", "rb");

		if (!fp)
		{
			printf("Could not open file\n");
			errorStatus = CANT_OPEN_FILE;
		}
	}

	if (errorStatus == NO_ERROR)
	{
		aCustomer.name[0] = '\0';
		aCustomer.streetAddress1[0] = '\0';
		aCustomer.streetAddress2[0] = '\0';
		aCustomer.city[0] = '\0';
		aCustomer.state[0] = '\0';
		aCustomer.zip = 0;

		if (fread((void *)(&aCustomer),sizeof(customer),1,fp) != 1)
		{
			errorStatus = FILE_IO_ERROR;
		}
		else
		{
			printf("%s\n",aCustomer.name);
			printf("%s\n",aCustomer.streetAddress1);
			printf("%s\n",aCustomer.streetAddress2);
			printf("%s\n",aCustomer.city);
			printf("%s\n",aCustomer.state);
			printf("%u\n",aCustomer.zip);
			printf("Press Enter to continue...");
			getchar();
		}
	}

	if (fp)
	{
		fclose(fp);
	}

	return (errorStatus);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -