我正在尝试从文件中读取结构。一切正确,直到我关闭我的应用程序并再次尝试读取数据。
进程终止,状态为-1073741819(0分钟,6秒)
我的代码: logika.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "logika.h"
int write_struc(char *PF, char *DF, char *TF, char *TL)
{
struct MYSTR myStruct ={PF, DF, TF, TL};
FILE* fb;
if ((fb=fopen(PLIK_DAT, "a"))!=NULL)
{
fwrite(&myStruct, sizeof(struct MYSTR), 1, fb);
fclose(fb);
return 1;
}
else
{
return 0;
}
}
void read_struc()
{
FILE* fb;
struct MYSTR myStruct;
fb = fopen(PLIK_DAT, "r");
while(1) {
fread(&myStruct,sizeof(struct MYSTR),1,fb);
if(feof(fb)!=0)
break;
printf("%s",myStruct.PF);
printf("%10s" ,myStruct.DF);
printf("%10s" ,myStruct.TF);
printf("%10s\n", myStruct.TL);
}
fclose(fb);
}
logic.h
#ifndef LOGIKA_H_INCLUDED
#define LOGIKA_H_INCLUDED
#define PLIK_DAT "baza.dat"
int write_struc(char *PF, char *DF, char *TF, char *TL);
struct MYSTR{
char *PF;
char *DF;
char *TF;
char *TL;
};
#endif // LOGIKA_H_INCLUDED
我尝试过二进制写入/读取,但这无济于事。
答案 0 :(得分:7)
您的结构包含4个地址。这些地址在程序之外毫无意义。如果您期望字符串数据(结构中包含的地址处的内容)被写出,则必须自己做,并设计一种文件格式,以允许您在输入时重建数据。>
在程序的一次执行中,您会得到“好运”,因为这些地址上的数据没有更改,因此看起来像是可以正常工作。但这没什么用。
答案 1 :(得分:0)
以下建议的代码:
注意:我将头文件合并到了主代码中,您可能不想这样做。
现在,建议的代码:
#ifndef LOGIKA_H_INCLUDED
#define LOGIKA_H_INCLUDED
// prototypes
int write_struc(char *PF, char *DF, char *TF, char *TL);
void read_struc( void );
#define MAX_STRING_LEN 1024
struct MYSTR
{
char PF[ MAX_STRING_LEN ];
char DF[ MAX_STRING_LEN ];
char TF[ MAX_STRING_LEN ];
char TL[ MAX_STRING_LEN ];
};
#endif // LOGIKA_H_INCLUDED
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
//#include "logika.h"
#define MAX_BUF_LEN 256
#define PLIK_DAT "baza.dat"
int write_struc(char *PF, char *DF, char *TF, char *TL)
{
struct MYSTR myStruct;
strncpy( myStruct.PF, PF, MAX_STRING_LEN );
strncpy( myStruct.DF, DF, MAX_STRING_LEN );
strncpy( myStruct.TF, TF, MAX_STRING_LEN );
strncpy( myStruct.TL, TL, MAX_STRING_LEN );
FILE* fb;
if ( !(fb=fopen(PLIK_DAT, "a")))
{
char buffer[ MAX_BUF_LEN ];
sprintf( buffer, "fopen to append to %s failed", PLIK_DAT );
perror( buffer );
return 0;
}
// implied else, fopen successful
if( fwrite(&myStruct, sizeof(struct MYSTR), 1, fb) != 1)
{
perror( "fwrite failed" );
return 0;
}
// implied else, fwrite successful
fclose(fb);
return 1;
}
void read_struc()
{
struct MYSTR myStruct;
FILE* fb;
if( !(fb = fopen(PLIK_DAT, "r") ) )
{
char buffer[ MAX_BUF_LEN ];
sprintf( buffer, "fopen to read %s failed", PLIK_DAT );
perror( buffer );
exit( EXIT_FAILURE ); // if program can recover, then use `return;` rather than `exit()`
}
// implied else, fopen successful
while( fread(&myStruct,sizeof(struct MYSTR),1,fb) == 1)
{
printf("\n%s", myStruct.PF);
printf("%s", myStruct.DF);
printf("%s", myStruct.TF);
printf("%s\n", myStruct.TL);
}
fclose(fb);
}