C:尝试从 .dat 文件读取 int 时访问错误 [英] C: Getting Bad access upon trying to read int from .dat file

查看:66
本文介绍了C:尝试从 .dat 文件读取 int 时访问错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取一个整数文件并在读取它们时打印它们.但是,我在循环的第一次迭代中遇到了错误的访问.任何想法为什么?

I am trying to read a file of integers and print them as I read them. However I am getting bad access on the first iteration through the loop. Any ideas why?

#include <stdio.h>

int main(int argc, const char * argv[])
{

    FILE *fr = fopen("testdata1.dat","r");
        int output;
        do {
            fscanf(fr, "%d", &output);

            printf("%d", output);
        }
        while(output != EOF); // check to make sure user has input
}

.dat 的前几行是

1000 0 100 2 90 2 80 3 70 2 60 2 10 -99
1001 8 80 2 80 2 50 3 70 2 40 2 10 -99

推荐答案

#include <stdio.h>

int main(int argc, char *argv[]){
FILE *fr = (FILE*) fopen("test.dat","r");

// ERROR HERE: fr=fopen("test.dat","r");
int output;
if(!feof(fr)){
 do {
    fscanf(fr, "%d", &output);

    printf("%d", output);
  }
   while(!feof(fr)); // check to make sure user has input
 fclose(fr);
 return 0;
}

使用此代码重试.

除了不正确的权限,找不到文件之外,我想不出任何问题..

I can't think of any problems other than incorrect permissions, unfindable file..

这篇关于C:尝试从 .dat 文件读取 int 时访问错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆