【问题标题】:C11 Bus error:10C11 总线错误:10
【发布时间】:2016-07-14 05:36:22
【问题描述】:

我是 C 的新手,我目前只是试图读取内容为“6”的文件,没有别的。每当我运行该文件时,我都会得到:总线错误:10。

#include <stdio.h>
#include <stdlib.h>
char input(void);

int main(int argc, char** argv)
{


    input();

    return (EXIT_SUCCESS);
}

char input(void)
{
    FILE *fp;
    char *score;

    fp = fopen("data.bin", "rt");


    fscanf(fp,"%s", score);

    printf("%s", score);

    fclose(fp);

}

【问题讨论】:

  • score 没有指向任何内容,但您尝试使用fscanf 读取它所指向的内存。
  • score 被称为 pointer 而不是 array 是有充分理由的。让两种不同的类型表现相同是毫无用处的。

标签: c


【解决方案1】:

我这样修改了你的代码:

#include <stdio.h>
#include <stdlib.h>

void input(void);

int main(int argc, char** argv) {
    input();
    return(EXIT_SUCCESS);
}

void input(void) {
    char buffer[10];
    FILE *ptr;
    ptr = fopen("data.bin","rb");  // r for read, b for binary
    fread(buffer, sizeof(buffer), 1, ptr); // read 10 bytes to our buffer
    printf("%s", buffer);

    fclose(ptr);
}

输出:

6

更多信息,请阅读:Read/Write to binary files in C

【讨论】:

    猜你喜欢
    • 2017-07-06
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多