0

I had to write a simple database (console application) in C: You could input gender, name and adress of people and the data would be saved in an array of structs called 'Person'. You could then also display all entries or delete entries again. So far so good.

Now I have to add functions to save the data into a .csv file and read from it again. However, the function fopen() always returns a NULL-pointer, so I can't even get to the reading or writing part. Below is my code. I hope you can tell me why not even this first step is working. I'm rapidly losing any confidence I had in my C abilities.

void save(Person persons[]) {
    char name[LEN];
    printf("File Name: ");
    fgets(name, LEN, stdin);
    fflush(stdin);
    name[strlen(name)] = '\0';

    FILE *file = fopen(name, "wx");
    if (!file) {
        printf("The file couldn't be created.\n\n");
    }
}
RalphBear
  • 75
  • 1
  • 12
  • 1
    name[strlen(name)] = '\0'; doesn't make sense because strlen needs a null terminator to determine the length of the string. – nicomp Jul 14 '21 at 13:41
  • 1
    `fflush(stdin)` is wrong, you also `NULL` terminate again. Why? – alex01011 Jul 14 '21 at 13:41
  • 1
    print the error number to see what's up. – nicomp Jul 14 '21 at 13:41
  • Good to know that null-terminating in this context doesn't make any sense. This line is literally copied from my professor. xd – RalphBear Jul 14 '21 at 13:42
  • 1
    `perror("file: ")` in the ifs scope... – alex01011 Jul 14 '21 at 13:42
  • 3
    Your professor has just tried to teach you a *very* bad habit. `fgets` reads a line of text, and gives you that line as a string, *including the trailing newline, `\n`*. So you often have to strip the newline back off. But blindly removing the last character -- assuming it's the `\n` -- is a terrible idea, because there are plenty of circumstances under which the last character is *not* a `\n`, after all. See [this question](https://stackoverflow.com/questions/2693776) for recommended techniques to strip the newline after calling `fgets`. – Steve Summit Jul 14 '21 at 13:47
  • @SteveSummit actually, it is even worse. It is not even stripping the last character but just writing 0 byte *after* last character. – Gerhardh Jul 14 '21 at 14:08
  • 1
    Are you sure that your professor did not add a `-1` to the index? – Gerhardh Jul 14 '21 at 14:09
  • 1
    If the line `name[strlen(name)] = '\0';` is from your professor and if this is not part of a question like "Find all problems in this code", he should be fired. – Jabberwocky Jul 14 '21 at 14:10

1 Answers1

0

why not even this first step is working.

fopen(name, "wx") certainly returns NULL as name contains '\n'. Improbable that such a file name exists.

See Removing trailing newline character from fgets() input.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256