简体   繁体   English

从文件中打印错误的值

[英]Printing of wrong value from a file

I tried the following code to write a structure to a file: 我尝试了以下代码将结构写入文件:

#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);
}

When I try to read the following file using : 当我尝试使用读取以下文件时:

#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);
    }
}

When I run the last program,the values printed are: 当我运行上一个程序时,输出的值是:

abcd 7 abcd 7

Well first field "abcd" is rightly printed,but the next value printed is 7,though I tried to write 55 in the file.What is going wrong? 好吧,第一个字段“ abcd”正确打印,但是下一个打印的值是7,尽管我尝试在文件中写入55。出了什么问题?

It's because you read the integer value 55 as a character , and in the ASCII alphabet the value 55 is the same as the character '7' . 这是因为您将数值55读取为字符 ,而在ASCII字母中,值55与字符'7'

You need to read the structure the same way you write it, using fread . 您需要使用fread以相同的方式读取结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM