从文件中打印错误的值

时间:2013-06-29 11:31:13

标签: c file-io

我尝试使用以下代码将结构写入文件:

#include<stdio.h>

struct record
{
char name[80];
int roll;
};

int main( )
{
    FILE* p=NULL;
    int length=0;
    char* file="abcd.txt";
    struct record r1={"abcd",55};
    p=fopen(file,"w");
    if (p==NULL)    {
        printf("Error in opening file");
    }
    length=sizeof(r1);
    fwrite(&r1,length,1,p);
    fclose(p);
    printf("Written successfully\n");
    free(r1);
}

当我尝试使用以下文件阅读以下文件时:

#include<stdio.h>

main( )
{
    int c;
    FILE* p=NULL;
    p=fopen("abcd.txt","r");
    if (p)  {
        while ((c=getc(p)) != EOF)
            putchar (c);
        fclose(p);
    }
}

当我运行最后一个程序时,打印的值为:

ABCD 7

第一个字段“abcd”正确打印,但是打印的下一个值是7,尽管我试图在文件中写入55.出了什么问题?

1 个答案:

答案 0 :(得分:3)

这是因为你将整数55读作字符,而在ASCII字母表中,值55与字符{{1}相同}}

您需要使用'7'以相同的方式阅读结构。

相关问题