【问题标题】:How do I open a binary file using a string? Using C如何使用字符串打开二进制文件?使用 C
【发布时间】:2011-08-29 00:19:13
【问题描述】:

我的印象是,要使用字符串打开二进制文件,您可以简单地创建字符串,然后将其实现为它将读取字符串的文件名。这就是我的讲义所陈述的。但是我显然错过了一些东西。我在 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);
}

【问题讨论】:

  • 最小代码示例。
  • scanf("%s", name); 是正确的。在下方添加printf ("The filename read is %s\n",name); 进行确认。

标签: c string fopen binaryfiles


【解决方案1】:

你可能想说

scanf("%s", &name[0]);

甚至只是:

scanf("%s", name);

您的 &amp;name[SIZE] 指向 name + SIZE,它超出分配的内存。

【讨论】:

  • 现在有什么问题?您能否在调用fopen 之前打印该字符串并验证它是否正确?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-30
  • 1970-01-01
  • 2011-09-09
  • 2017-06-06
相关资源
最近更新 更多