| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1020 人关注过本帖
标题:求助
只看楼主 加入收藏
dpj149
Rank: 2
等 级:论坛游民
帖 子:14
专家分:28
注 册:2018-2-9
收藏
 问题点数:0 回复次数:3 
求助
这段代码中为什么写入文件的数据全是乱码,第二次打开文件出错,程序直接退出了,是什么原因?
//randbin.c--用二进制I/O进行随机访问
#include<stdio.h>
#include<stdlib.h>
#define ARSIZE 1000

int main(void)
{
    double numbers[ARSIZE];
    double value;
    const char * file = "numbersdat";
    int i;
    long pos;
    FILE *iofile;

    //创建一组double类型的值
    for (i = 0; i < ARSIZE; i++)
    {
        numbers[i] = 100.0*i + 1.0 / (i + 1);
    }
    //尝试打开文件
    if ((iofile = fopen(file, "wb")) == NULL)
    {
        fprintf(stderr, "Could not open %s for output.\n", file);
        exit(EXIT_FAILURE);
    }
    //以二进制格式把数组写入文件
    fwrite(numbers, sizeof(double), ARSIZE, iofile);
    fclose(iofile);
    if ((iofile = fopen(file, "rb")) == NULL);
    {
        fprintf(stderr, "Could not open %s for random access.\n", file);
        exit(EXIT_FAILURE);
    }
    //从文件中读取选定的内容
    printf("Enter an index in the range 0-%d.\n", ARSIZE - 1);
    while (scanf("%d", &i) == 1 && i >= 0 && i < ARSIZE)
    {
        pos = (long)i * sizeof(double);  //计算偏移量
        fseek(iofile, pos, SEEK_SET);
        fread(&value, sizeof(double), 1, iofile);
        printf("The value there if %f.\n", value);
        printf("Next index (out of range to quit):\n");
    }
    //完成
    fclose(iofile);
    puts("Bye!");

    return 0;
}

[此贴子已经被作者于2018-11-26 16:12编辑过]

搜索更多相关主题的帖子: 文件 double value file for 
2018-11-26 16:09
吹水佬
Rank: 16Rank: 16Rank: 16Rank: 16
等 级:版主
威 望:451
帖 子:10538
专家分:42927
注 册:2014-5-20
收藏
得分:0 
//if ((iofile = fopen(file, "rb")) == NULL);
if ((iofile = fopen(file, "rb")) == NULL)
2018-11-26 16:33
吹水佬
Rank: 16Rank: 16Rank: 16Rank: 16
等 级:版主
威 望:451
帖 子:10538
专家分:42927
注 册:2014-5-20
收藏
得分:0 
    //从文件中读取选定的内容
    fread(numbers, sizeof(double), ARSIZE, iofile);
    fclose(iofile);
    printf("Enter an index in the range 0-%d.\n", ARSIZE - 1);
    while (scanf("%d", &i) == 1 && i >= 0 && i < ARSIZE)
    {
        printf("The value there if %f.\n", numbers[i]);
        printf("Next index (out of range to quit):\n");
    }
2018-11-26 16:41
dpj149
Rank: 2
等 级:论坛游民
帖 子:14
专家分:28
注 册:2018-2-9
收藏
得分:0 
回复 2楼 吹水佬
眼睛真好使,我检查了好几遍了,非常感谢,终于正常了
2018-11-26 17:17
快速回复:求助
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.015301 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved