Search code examples
cprintffgets

fgets clears the contents of my C file and doesn't allow me to print to a file


I'm making a simple c program to add, display and modify records for a student. It makes a .txt file, which accepts the records.

Long story short, I've managed to isolate which function is clearing my file and it's fgets. For some strange reason, fprintf works normally until I reach fgets which then proceeds to clear my file every time it's used. I've been racking my brain for 4 days because of this.

int main(int argc, char *argv[])
{
    int changes = 1; /* numbers of changes made to text file */
    FILE *f;
    f = fopen(argv[1], "wb+");
    fprintf(f, "this is a success");
    if (argc < 2) {
        printf("You dun goof'd.");
        exit(1);
    }
    if (f == NULL)
        exit(1);
    input_again(f, changes);
    error(f, changes);
    fclose(f);
    return 0;
}

void input_again(FILE *f, int quantity)
{
    char command[MAX];
    /*char cmd[25];
    char arg1[30];
    char arg2[30];
    char arg3[30];*/
    int changes = quantity;
    fprintf(f, "input again%d", changes);
    while ((fgets(command, MAX, stdin)) != NULL) { /* file gets cleared after input */
        printf("%s", command);
        sscanf(command, "%s %s %s %s", cmd, arg1, arg2, arg3);
        if (strlen(arg1) > 21 || strlen(arg2) > 21 || strlen(arg3) > 21)
            error(f, changes);
        if (strcmp(cmd, "add") == 0) {
            fprintf(f, "add");
            add(f, arg1, arg2, arg3, changes);
            printf("%d", changes);
        } else if (strcmp(cmd, "display") == 0) {
            display(f, arg1, changes);

        } else if (strcmp(command, "modify")== 0) {
            modify(f, arg1, changes);
        } else {
            error(f, changes);
        }*/
    }
}

I'm using cygwin to compile my program. If there's a simple problem with how I'm calling my code, please let me know.


Solution

  • you are writing the file named on the command line argv[1], but do you mean to be reading stdin? That won't read what you just wrote.