gpt4 book ai didi

c - 使用 fopen_s 打开文件流时出现未处理的异常访问冲突

转载 作者:行者123 更新时间:2023-11-30 19:29:23 25 4
gpt4 key购买 nike

我很难弄清楚为什么我的代码无法工作。

该程序的目标是从给定的数组中生成一系列随机句子,然后将它们输出到屏幕或文本文件。

我不太确定问题是什么,但是当我输入文件标题时,我收到一个未处理的异常错误。

如果我将 FILE** 流参数更改为 NULL,而不是写入 fopen_s,则会出现调试断言错误。

我相信问题出在我声明指针的方式上。

#include <.stdio.h>
#include <.conio.h>

int main()
{
char * article[5] = { "the", "one","some","any","a" };
char * noun[5] = { "boy","girl","dog","town","car" };
char * verb[5] = { "drove","jumped","ran","walked","skipped" };
char * preposition[5] = { "to","from","over","under","on" };
int x = 0;
char * output[100] = {0};

//char output = { "" };

FILE ** write = "C:\Users\dilli\Downloads\test.txt";

while (5) {
printf("Enter one(1) to output to screen, two(2) to output to file:\n");
scanf_s("%d",&x);
if(x==1)
printf_s("%s %s %s %s %s %s.\n", article[rand() % 5], noun[rand() % 5], verb[rand() % 5],
preposition[rand() % 5], article[rand() % 5], noun[rand() % 5]);
else if (x == 2)
{
printf("Enter name of output file:\n");
scanf_s("%s",&output,100);
printf("output:\n%s",output);
fopen_s(write,output, "w");//This is where we are getting an unhandled exception.
fprintf("%s %s %s %s %s %s.\n", article[rand() % 5], noun[rand() % 5], verb[rand() % 5],
preposition[rand() % 5], article[rand() % 5], noun[rand() % 5]);
fclose(write);
}
}
}

最佳答案

首先,您不能将字符串文字分配给FILE**变量。那甚至不应该编译。无论如何,您甚至没有使用字符串文字,因为您正在提示用户输入输出文件名。所以只需去掉字符串文字即可。

其次,您滥用了 fopen_s()scanf_s(),这就是您的代码崩溃的原因。

  • 当提示用户输入文件名时,您要求 scanf_s() 读入指针数组而不是字符数组。仅此一点就可能会崩溃,或者至少在您稍后尝试访问数组的内容时导致未定义的行为。

  • 之后,您将无效的 FILE** 指针和无效的 char[] 数组传递给 fopen_s().它希望您传递一个指向有效 FILE* 变量的指针和一个以 null 结尾的 char 字符串,而不是 char* 指针数组.

第三,您根本没有将打开的 FILE* 传递给 fprintf()

话虽如此,试试这个:

#include <stdio.h>
#include <conio.h>

int main()
{
const char* article[5] = { "the", "one","some","any","a" };
const char* noun[5] = { "boy","girl","dog","town","car" };
const char* verb[5] = { "drove","jumped","ran","walked","skipped" };
const char* preposition[5] = { "to","from","over","under","on" };
char fileName[260] = {0};
FILE *write = NULL;
int i, x;

for (i = 0; i < 5; ++i) {
printf("Enter one(1) to output to screen, two(2) to output to file:\n");
x = 0;
scanf_s("%d", &x);
if (x == 1) {
printf_s("%s %s %s %s %s %s.\n", article[rand() % 5], noun[rand() % 5], verb[rand() % 5], preposition[rand() % 5], article[rand() % 5], noun[rand() % 5]);
}
else if (x == 2) {
printf("Enter name of output file:\n");
scanf_s("%s", fileName, 260);
printf("output:\n%s", fileName);
if (fopen_s(&write, fileName, "w") == 0) {
fprintf(write, "%s %s %s %s %s %s.\n", article[rand() % 5], noun[rand() % 5], verb[rand() % 5], preposition[rand() % 5], article[rand() % 5], noun[rand() % 5]);
fclose(write);
}
}
}

return 0;
}

关于c - 使用 fopen_s 打开文件流时出现未处理的异常访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52826934/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com