我在fscanf_s
功能上遇到问题。
我编写了一个代码,询问用户是否有用于输入数据的文件,如果这样做,它将读取数据并将值输入结构。好吧,这不起作用。
我试图自己找到一个错误,但是失败了,所以我在这里寻求帮助。
用户输入输入内容的第一部分,程序将根据输入的内容创建一个文本文件,但是您可以看到扫描部分不起作用。任何帮助都会很棒。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define size 10
char *filename = "file.txt";
char savefile[20];
struct Employee
{
char name[20];
float rate;
float hours;
}employee;
int main(void)
{
FILE *file;
FILE *output;
FILE *input;
int count = 0;
int yn;
int x = 0; int q = 0;
int o = 0; int k = 0;
int y = 0; int i = 0;
struct Employee guys[size];
printf("Do you have a file? 1. Yes 2. No\n");
scanf_s("%d", &yn);
if (yn == 2)
{
errno_t err = fopen_s(&file, filename, "w");
for (q = 0; q < size; q++)
{
puts("\ntype name: (type -1 to quit) \n");
scanf_s("%s", &guys[q].name, 20);
if (strcmp(guys[q].name, "-1") == 0) { break; }
puts("\ntype hourly rate: (type -1 to quit)\n");
scanf_s("%f", &guys[q].rate);
if (guys[q].rate == -1) { break; }
puts("\ntype hours worked: (type -1 to quit)\n");
scanf_s("%f", &guys[q].hours);
if (guys[q].hours == -1) { break; }
count++;
}
for (int q = 0; q < count; q++)
{
fprintf(file, "%s %f %f\n", guys[q].name,guys[q].rate, guys[q].hours);
}
fclose(file);
}
if (yn == 1)
{
errno_t err = fopen_s(&input, filename, "r");
if (err != 0)
{
printf("Unable to open up %s", filename);
return;
}
while (!feof(input))
{
fscanf_s(file, "%s" "%f" "%f", &guys[i].name,20,&guys[i].rate, &guys[i].hours);
i++;
}
fclose(input);
}
我将在第一部分中创建的文件用作第二部分的输入。我还测试了没有feof循环的fscanf_s()。同样的问题仍然发生。错误不断弹出,指出在program05.exe中的0x77506165(ntdll.dll)处引发了异常:0xC0000005:访问冲突写入位置0xCCCCCCF0。
最佳答案
您的读取代码中有两个问题会导致崩溃。
您正在将关闭的文件指针传递给fscanf_s
函数。fclose(file);
您正在将无效地址20
传递给fscanf_s函数。
fscanf_s(file, "%s" "%f" "%f", &guys[i].name,20,&guys[i].rate, &guys[i].hours);
应该更改为
fscanf_s(input, "%s" "%f" "%f", &guys[i].name,&guys[i].rate, &guys[i].hours);
我建议您不要使用
while (!feof(input))
相反,请采用以下方法。
while (fscanf_s(input, "%s %f %f", &guys[i].name,&guys[i].rate, &guys[i].hours) == 3)
{
i++;
}
关于c - 将值从文本文件扫描到结构中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51805977/