我的任务是读取文件( datain.txt ),将其转换为二进制文件,最后再次读取二进制文件以打印出该文件中的信息。
我已经多次尝试调试我的代码,但发现该错误发生在函数convertfile
中。有关详细信息,文件指针datain
不会四处移动,而只是读取第一行。我认为fscanf
移动了指针,但是在这种情况下是错误的。因此,动态存储器input
的数据完全不变。
->输出:
0 0 0 0
我使用的文件输入:
1 JoeyMathel 0385788060 joeymathel@gmail.com
2 ScottyJack 0325621458 scottyjack@gmail.com
3 JohnMarker 0230125214 johnmarker@gmail.com
4 KarlKarper 0213020352 karlkarper@gmail.com
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAXWORD 100
typedef struct address address;
struct address
{
int stt;
char name[100], telephone_number[20], email[100];
};
bool checktoread(FILE *in)
{
return in == NULL;
}
void inputdata(FILE *datain, int max, address *array)
{
while(fread(array, sizeof(address), max, datain)>0);
}
void convertfile(FILE *datain, FILE *dataout, int max)
{
address *input = (address *)malloc(sizeof(address)*max);
int size = sizeof(address);
int i = 0;
while (i<max)
{
fscanf(datain, "%d", &input[i].stt);
fscanf(datain, "%s", input[i].name);
fscanf(datain, "%s", input[i].telephone_number);
fscanf(datain, "%s\n", input[i].email);
i++;
}
fwrite(input, size, max, dataout);
free(input);
}
void printout(address *directory, int max)
{
int i = 0;
for (; i < max; i++)
printf("%-4d%-20s%-20s%-30s\n", directory[i].stt, directory[i].name, directory[i].telephone_number, directory[i].email);
}
int countline(FILE *in)
{
int i = 0;
char string[100];
while(fgets(string, 100, in)!= NULL)
i++;
return i;
}
int main()
{
FILE *fpin = fopen("datain.txt", "r");
FILE *fpout = fopen("phonebook.dat", "rb+");
int max = countline(fpin);
rewind(fpin);
address *directory = (address *)malloc(sizeof(address)*max);
if (checktoread(fpin))
{
printf("This file is empty or unable to be opened\n");
exit(1);
}
convertfile(fpin, fpout, max);
rewind(fpin);
rewind(fpout);
fclose(fpin);
inputdata(fpout, max, directory);
printout(directory, max);
fclose(fpout);
free(directory);
return 0;
}
```