簡體   English   中英

fseek,fread並返回二進制文件功能中的指針(C)不能正常工作

[英]fseek, fread and return the pointer (C) in binary file function not working properly

我想將指針返回到我從文件中讀取的結構(它會轉到另一個基本上只打印數據的函數。)函數通過int sem獲取(序列號-1),然后進行設置我要用fseek讀取的指向結構開頭的文件指針,只需讀取整個結構並返回指針即可。 (示例:如果文件中寫入的結構數為5,而我想讀取4號結構,則函數獲得的sem值為3,然后使用fseek指針跳過前3個結構,函數讀取並返回構造4)。 如果sem值為0,它可以正常工作,但是當我尋找任何其他結構時,它就不會那么好。 我不知道出什么問題了! 救命? :)

type_seminar *file_seminars_search(int sem) {
     type_seminar *temp_s = (type_seminar*) malloc(sizeof(type_seminar));
     FILE *f_sem;
     if ((f_sem = fopen("seminars.bin", "r")) != NULL ) {
          fseek(f_sem, sem * sizeof(type_seminar), SEEK_SET);
          fread(temp_s, sizeof(type_seminar), 1, f_sem);
          fclose(f_sem);
          return (temp_s);
     } else
          printf("Cannot access file. \n ");
     return 0;
}

strucutre的定義:

typedef struct {
     char s_title[A];
     char s_street[B];
     char s_town[C];
     int max_no_teachers;
     int no_applied_teachers;
} type_seminar;

還有問題所在的打印數據的功能:

void seminar_details(type_seminar *temp_s) {
      printf("   SEMINAR TITLE : %s", temp_s->s_title);
      printf("   Street: %s ", temp_s->s_street);
      printf("   Town: %s", temp_s->s_town);
      printf("   Max no of applied teachers: %d \n", temp_s->max_no_teachers);
      printf("   No of applied teachers: %d \n", temp_s->no_applied_teachers);
}

我覺得workshops.bin的創建方式將決定文件的讀取方式。 與ascii模式相比,以二進制模式打開文件也可能會有所幫助。

我使用以下功能創建了Workshops.bin

void createData()
{
FILE    *fcre;
type_seminar element;
int counter;

fcre = fopen("seminars.bin", "wb");
for(counter = 0; counter < 5; counter++)
{
    printf("Enter type_seminar.s_title:");
    scanf("%s", element.s_title);
    printf("Enter type_seminar.s_street:");
    scanf("%s", element.s_street);
    printf("Enter type_seminar.s_town:");
    scanf("%s", element.s_town);
    printf("Enter type_seminar.max_no_teachers:");
    scanf("%d", &element.max_no_teachers);
    printf("Enter type_seminar.no_applied_teachers:");
    scanf("%d", &element.no_applied_teachers);

    fwrite(&element, sizeof(type_seminar), 1, fcre);
}
fclose(fcre);
}

我將原始文件中的幾行修改為

if ((f_sem = fopen("seminars.bin", "rb")) != NULL ) 

 fread(temp_s, sizeof(type_seminar), 1, f_sem);

通過這些更改,我可以使您的代碼按照您的預期設計工作!!

問題出在

return 0;

線。 因為您不返回int。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM