c - 如何读取数据和写入数据 C 编程
问题描述
#include <stdio.h>
#include <stdlib.h>
struct customer {
char fname[20],lname[20];
int acct_num;
float acct_balance;
};
void main ()
{
FILE *outfile;
struct customer input;
// open Accounts file for writing
outfile = fopen ("C:\\Users\\Admin\\Desktop\\read\\per.dat","w");
if (outfile == NULL)
{
fprintf(stderr, "\nError opening accounts.dat\n\n");
exit (1);
}
// instructions to user
printf("Enter \"stop\" for First Name to end program.");
// endlessly read from keyboard and write to file
while (1)
{
// prompt user
printf("\nFirst Name: ");
scanf ("%s", input.fname);
// exit if no name provided
if (strcmp(input.fname, "stop") == 0)
exit(1);
// continue reading from keyboard
printf("Last Name : ");
scanf ("%s", input.lname);
printf("Acct Num : ");
scanf ("%d", &input.acct_num);
printf("Balance : ");
scanf ("%f", &input.acct_balance);
// write entire structure to Accounts file
fwrite (&input, sizeof(struct customer), 1, outfile);
}
FILE *infile;
/*** open the accounts file ***/
infile = fopen ("C:\\Users\\Admin\\Desktop\\read\\per.dat","r");
if (infile == NULL)
{
fprintf(stderr, "\nError opening accounts.dat\n\n");
exit (1);
}
while (fread (&input, sizeof(struct customer), 1, infile))
printf ("Name = %10s %10s Acct Num = %8d Balance = %8.2f\n",
input.fname, input.lname, input.acct_num, input.acct_balance);
}
当我在程序中输入信息时,它只是在文件中写入随机字符.dat
并且不显示我写的信息。请帮我找出问题所在。
解决方案
你有:
if (strcmp(input.fname, "stop") == 0)
exit(1);
这将在此时结束您的程序。我不认为你想要那个。相反,打破你的循环:
if (strcmp(input.fname, "stop") == 0)
break;
此外,请务必在完成写入文件后和打开文件进行阅读之前关闭文件。否则,它可能不存在或输出到它可能不会被刷新:
fclose(outfile);
最后,请注意fwrite()
将写入结构的二进制数据。这对人眼来说就像垃圾一样,即使fread()
应该正确阅读。但请注意,您应该将文件作为二进制文件打开以进行读取和写入。否则,某些系统(至少是 Windows)将对数据进行一些解释。
outfile = fopen ("C:\\Users\\Admin\\Desktop\\read\\per.dat","wb");
infile = fopen ("C:\\Users\\Admin\\Desktop\\read\\per.dat","rb");
通过这些更改,您的代码对我来说似乎工作正常。
请注意,如果您使用不同的平台进行写入和读取、通过网络发送数据,或者甚至可能使用不同的编译选项,那么以这种方式写入和读取二进制数据可能会充满危险。字节顺序(“endianness”)、数据类型大小和结构填充都会给您带来问题。对于现实世界的问题,某种可移植的序列化会更好。
推荐阅读
- bash - 脚本用 SH 发送命令
- sql - 如何从一个列中获取不同的数据
- node.js - 如何在 NodeJS 中提取密钥大小
- python - splunklib.binding.HTTPError:HTTP 400 错误请求 - 未知搜索命令“索引”
- mongodb - 无法使用 expressjs 从 mongodb 获取数据
- xml - 使用 OdooV12 通过按钮调用操作
- sql - 接收每个 id 的一条记录和最新日期的一条记录
- python - 无法使用 python 烧瓶将箱线图渲染到 html 页面
- javascript - 如何检查数组中的项目?
- python - Django 休息框架 | Knox 身份验证密码未在数据库中散列