我的印象是,要使用字符串打开二进制文件,您可以简单地创建字符串,然后将其实现为将读取字符串的文件的名称。这是我的讲义所说的。但是我突然失去了一些东西。我已经在fopen中使用了& name,name和& name [SIZE],每次我都获得inBinFile == NULL,除非我使用注释行。我的字符串是正确的。怎么了?非常感谢帮助。提前谢谢。
#include <stdio.h>
#include <stdlib.h>
#define SIZE 25
int frstmenu(void);
int sndmenu(void);
int main()
{
int fmenu, smenu;
char name[SIZE];
FILE *inBinFile;
unsigned char numRead;
fmenu = frstmenu();
if ( fmenu !=1 && fmenu !=2 )
{
printf("\nIncorrect option\n");
fmenu = frstmenu();
}
if (fmenu == 1)
{
printf("\nEnter the file name: \n");
scanf("%s", &name[SIZE]);
/* printf("filename: %s", &name[SIZE]); */
smenu = sndmenu();
if (smenu !=1 && smenu !=2 )
{
printf("\nIncorrect option\n");
smenu = sndmenu();
}
if (smenu == 1)
{
inBinFile = fopen( name, "rb");
/* inBinFile = fopen( "stream.grc", "rb"); */
if (inBinFile == NULL)
{
fprintf(stderr, "Error opening %s", &name[SIZE]);
return(-1);
fclose(inBinFile);
}
}
return(0);
}
int frstmenu()
{
float selection;
printf("----Menu----\n");
printf("1 Open a file ( supported format: .grc )\n");
printf("2 Exit the program\n");
printf(" Please select an option (1 or 2): ");
scanf("%f", &selection);
return(selection);
}
int sndmenu()
{
int selection;
printf("---Menu---\n");
printf("1 Decode the sequence\n");
printf("2 Exit the program\n");
printf(" Please select an option (1 or 2):\n");
scanf("%i", &selection);
return(selection);
}
答案 0 :(得分:5)
你可能想说
scanf("%s", &name[0]);
甚至只是:
scanf("%s", name);
您的 指向&name[SIZE]
name + SIZE
,超出已分配的内存。