簡體   English   中英

從C中的.txt文件讀取最后一條記錄的困難

[英]difficulty with reading the last record from a .txt file in C

我正在用C編寫一個程序,該程序從用戶讀取文件數據(名稱,q1,q2,q3的答案),並將數據存儲在.txt文件中,並允許用戶查看他們輸入的數據。 目前,我在使用允許數據查看最后一條記錄的功能方面遇到困難。 這是我的代碼:

struct pre_survey{
char name[20];
int q1;
int q2;
int q3;
};
struct pre_survey temp;
struct pre_survey get;

int main(){
while (pre_or_post!=0){

if(pre_or_post==1){
    printf("\n1. append(enter) data\n");
    printf("2. check first record\n");
    printf("3. check last record\n");
    printf("please select your choice\n");
    scanf("%d", &choice);

switch (choice){
    case 1: append();
            break;
    case 2: frst_record();
            break;
    case 3: last_record();
            break;}}

void append(){
    fp=fopen("pre-survey.txt", "a");
    printf("name\n");
    scanf("%s", &temp.name);
    printf("q1:\n");
    scanf("%d", &temp.q1);
    printf("q2:\n");
    scanf("%d", &temp.q2);
    printf("q3:\n");
    scanf("%d", &temp. q3);
    fprintf(fp, "%s %d %d %d", temp.name, temp.q1, temp.q2, temp.q3);
    fclose(fp);}

void last_record(){
    fp=fopen("pre-survey.txt", "r");
    fseek(fp, -sizeof(temp),SEEK_END);
    fscanf(fp, "%s %d %d %d", get.name, &get.q1, &get.q2, &get.q3);
    printf("name: %s\n", get.name);
    printf("q1: %d\n", get.q1);
    printf("q2: %d\n", get.q2);
    printf("q3:%d\n", get.q3);
    fclose(fp); 
}

現在,當我嘗試查找最后一條記錄時,將顯示第一條記錄的數據。 我認為問題是,當我檢查sizeof(temp)為32時,以及當我使用

fp=fopen("pre-survey.txt", "r");
fseek(fp,0, 2);
size=ftell(fp);
printf("size:%d\n", size);

要檢查整個文件的大小,它是34。因此,當我按temp的大小從文件末尾讀取時,它將轉到第一條記錄。 但是我不確定代碼中做錯了什么。

如果通過fseek讀取記錄的位置,則Record必須為固定長度。

例如

void append(void){
    FILE *fp=fopen("pre-survey.txt", "a");
    printf("name\n");
    scanf("%19s", temp.name);
    printf("q1:\n");
    scanf("%d", &temp.q1);
    printf("q2:\n");
    scanf("%d", &temp.q2);
    printf("q3:\n");
    scanf("%d", &temp. q3);
    //32bit system MAX_INT : 2147483647 (10digits)
    //19char  2digit 2digit 2digit\n total:30 (windows:31(\n->CRLF)
    fprintf(fp, "%-20s%3d%3d%3d\n", temp.name, temp.q1, temp.q2, temp.q3);
    fclose(fp);
}

void last_record(void){
    FILE *fp=fopen("pre-survey.txt", "rb");
    //fseek(fp, -31, SEEK_END);//for windows
    fseek(fp, -30, SEEK_END);
    fscanf(fp, "%s %d %d %d", get.name, &get.q1, &get.q2, &get.q3);
    printf("name: %s\n", get.name);
    printf("q1: %d\n", get.q1);
    printf("q2: %d\n", get.q2);
    printf("q3: %d\n", get.q3);
    fclose(fp); 
}

暫無
暫無

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

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