我的函數寫入到文件中:的fscanf()不與輸入工作
Record_t * load_Record(FILE * infile)
{
Record_t *r;
char title[TITLE_SIZE];
char [MEDIUM_SIZE];
int ID, rating;
if ((fscanf(infile,"%d: %s %d", &ID, medium, &rating) != 3 && fgets(title, TITLE_SIZE, infile))){
return NULL;
}
printf("medium is: %s title is: %s\n", medium, title);
r = create_Record(medium, title);
set_Record_rating(r, rating);
return r;
}
其中Record_t定義爲:
typedef struct Record {
int ID;
char * title;
char * medium;
int rating;
} Record_t;
我的主要:
#include "Record.h"
#include <stdlib.h>
int main()
{
char * title = "The Queen";
char * medium = "DVD";
FILE * pfile ;
struct Record *t = create_Record(medium, title); //creates a record
struct Record *s;
set_Record_rating (t, 3);
print_Record(t);
pfile = fopen("output.txt", "w");
save_Record(t, pfile);
fclose(pfile);
destroy_Record(t); //de-allocates memory
pfile = fopen("output.txt", "r");
if(!(s = load_Record(pfile))){
return 1;
}
print_Record(s);
fclose(pfile);
destroy_Record(s);
return 0;
}
輸出。 txt寫入文件後:
1: DVD 3 The Queen //checked for excess whitespace(has newline however)
端子輸出:
1: The Queen DVD 3
medium is: DVD title is: � //title being saved inappropriately
@
2: �
@ DVD 3
現在我與fgets功能是錯誤的!出於某種原因,標題被不適當地保存
我對下列標誌編譯: GCC -ansi -std = C89 -pedantic -Wmissing的原型-Wall test.c的Record.c -o測試
其中test.c的是我的主要
您尚未爲您的緩衝區分配任何內存,即「medium」。事實上,在使用它之前,你甚至不會初始化變量。 – 2012-01-18 02:11:38