从C中的.txt文件中读取最后一条记录的困难

时间:2016-05-19 18:42:07

标签: c file-io fseek

我正在用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的大小从文件的末尾读取时,它会转到第一个记录。 但我不确定我在代码中做错了什么。

1 个答案:

答案 0 :(得分:0)

如果要按fseek读取记录的位置, 记录必须是固定长度。

E.g。

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); 
}
相关问题