-1

I'm programming in code::blocks and I got problem reading file here is the code:

            char fileName[] ="";
            fflush(stdin);
            E11: printf("\n\tEnter the @ Mac (X:X:X:X:X:X) in Hex :");
            gets(MAC);
            E12: printf("\n\tEnter file name:");
            gets(fileName);
            FILE* fichier;
            fichier = fopen(fileName,"r");
            if (fichier == NULL)
            {
                printf("Error! Try Again");
                goto E12;
            }
            else
            {
                printf("sending Data....");
                //TODO..
            }
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261

4 Answers4

3

First of all, don't use gets(), use fgets() instead.

gets() seriously suffers from buffer overrun issue, which can be avoided by using fgets().

That said, coming to the main issue in your code, by saying

char fileName[] ="";

you're allocating a 1-char array, which is not enough to hold the input, anyway.

You should change that to

char fileName[64] = {0};

or something similar.

Also, fflush(stdin); is against the C standard, it invokes undefined behavior. Remove that statement.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

This program exhibits undefined behavior. filename is a char array with only one element. Try changing the declaration to char fileName[256] = "";

owacoder
  • 4,815
  • 20
  • 47
0
  1. fflush(stdin) is undefined behavior.
  2. gets is bad. From man gets:

    Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.

    (Emphasis and code formatters added.)

  3. The definition

    char fileName[] = "";
    

    only allocates one byte of memory because sizeof("") == 1. You need a more flexible approach, which is another argument for fgets. Just allocate some arbitrary number of bytes probably capable of storing the whole input and pass that size to fgets:

    char fileName[32];
    
    ...
    
    fgets(fileName, sizeof(fileName), stdin);
    
  4. goto is bad.

Community
  • 1
  • 1
cadaniluk
  • 15,027
  • 2
  • 39
  • 67
0

thank you all:

after trying and trying if found that the problem is the file that i'm trying to read which is lorem ipsum that i copied from: here. i can't belive it, it is so strange..

thanks for the answers.