【问题标题】:How to use simple file input and output in C如何在 C 中使用简单的文件输入和输出
【发布时间】:2013-12-24 22:58:41
【问题描述】:

谁能告诉我应该如何在 C 中执行基本的文件输入和输出。我尝试搜索,但只能找到 C++ 等的解决方案。

我正在尝试使用 fscanf 和 fprintf 来执行此操作。但是,程序在执行此部分后立即崩溃,并显示错误消息:“Test Project.exe 中 0x50D39686 (msvcr120d.dll) 处的未处理异常:0xC0000005:访问冲突写入位置 0xCCCCCCCC。”文件cats.txt位于 Documents\Visual Studio 2013\Projects\Test Project\Test Project 我的代码粘贴在下面

#include <stdio.h>

#include <stdlib.h>
#include <string.h>
#include <math.h>

int main()

{
    double things_in_file[6];
int counter;
FILE *file_cats;

if ((file_cats = fopen("cats.txt", "r")) == NULL)
{
    printf("This file doesn't exist.\n");
    system("pause");
    exit(-1);
}

for (counter = 0; counter <= 5; counter = counter + 1)
{

    fscanf(file_cats, "%lf\n", &things_in_file[counter]);
    printf("%f\n", things_in_file[counter]);

}

fclose("file_cats");
system("pause");

exit(0);

}


我知道出了什么问题。 fclose("file_cats") 应该是 fclose(file_cats)。这解决了我的问题。

【问题讨论】:

  • counter &lt;= 5 应该是 counter &lt; 5 和 fscanf ... &amp;things_in_file[counter]
  • @BLUEPIXY - 你的评论应该是一个答案。并告诉 OP 他超出了数组缓冲区。
  • 您在 MS VS 2013 中编程的事实与这个问题无关。从文件中读取是标准的,无论使用何种 IDE 都应该可以工作。
  • 我刚刚将数组的维度从 5 更改为 6。但我仍然收到此错误消息:“Test Project.exe 中 0x50F79686 (msvcr120d.dll) 处的未处理异常:0xC0000005:访问冲突写入位置 0xCCCCCCCC。”
  • 抱歉,我刚刚注意到注释指出了 fscanf 函数中缺少的“&”。我也修好了。我确实从黑色窗口中列出的 cat.txt 中获取了值,但不久后我收到此消息:“Test Project.exe 中 0x50DC7EEB (msvcr120d.dll) 处的未处理异常:0xC0000005:访问冲突写入位置 0x00EE58D8。”跨度>

标签: c visual-studio input output


【解决方案1】:

数组声明例如array[5] 是5 个元素,索引从0 到4 (0,1,2,3,4)

scanf需要变量的地址来存储值

【讨论】:

    猜你喜欢
    • 2016-08-16
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多