编程论坛's Archiver

duffebear 发表于 2008-5-12 19:05

文本文件与二进制文件区别

刚刚写的一个文件写、读的小程序, 将数组arrayInt的元素写入 文件 ,在从文件中读取放到数组b中,分别测试了两种文件类型,使用二进制文件读写没有任何问题,而使用文本文件读出到b中从第8个元素开始出错。  详情看附后截图:

//开发环境:devcpp 4.9.9.2
#include<stdio.h>
#include<stdlib.h>
#define NUM 30

int main(void)
{
    FILE* fp;
    int arrayInt[NUM];
    int b[NUM];  //从文件读出时放到此数组
    int i;
    //数组初始化
    for(i=0;i<NUM;++i)
    {
           arrayInt[i]=3*i+2;
    }
   
    //输出
    printf("打印数组arrayInt:\n");
    for(i=0;i<NUM;i++)
    {
        printf("arrayInt[%d]=%d\t",i,arrayInt[i]);  
    }
   
     if((fp = fopen("D:\\1.dat","wb+"))==NULL)
//  if((fp = fopen("D:\\1.txt","wt+"))==NULL)   //NUM超过8就出问题
    {
           printf("unable to open 1.txt\n");
           exit(1);
    }

    /*-----------------------------------------------------   
    //函数fwrite数据写入文件
    函数名: fwrite
    功  能: 写内容到流中
    用  法: int fwrite(void *ptr, int size, int nitems, FILE *stream);
    ----------------------------------------------------------*/
    for(i=0;i<NUM;i++)
    {
        fwrite(&arrayInt[i],sizeof(int),1,fp);   
    }
   
    //重新定位文件指针到文件首
    rewind(fp);
     
    //函数fread将数据读出文件
    for(i=0;i<NUM;i++)
    {
        fread(&b[i],sizeof(int),1,fp);   
    }

    //输出
    printf("打印数组b:\n");
    for(i=0;i<NUM;i++)
    {
        printf("b[%d]=%d\t",i,b[i]);  
    }
    fclose(fp);
    system("pause");
    return 0;
}

duffebear 发表于 2008-5-12 19:07

不好意思,运行截图发不上来

页: [1]

Powered by Discuz! Archiver 6.1.0  © 2001-2007 Comsenz Inc.