Chris Loonam
Chris Loonam

Reputation: 5745

fprintf not working C

I'm trying to make a simple program that writes to a .txt file, but this code won't work.

#include <stdio.h>
#include <string.h>
#include "main.h"

int main(int argc, const char * argv[])
{
    FILE *f = fopen("text.txt", "w+");
    char c[256];
    printf("What's your name?\n");
    scanf("%s", c);
    fflush(f);
    if (c!=NULL) 
    {
        printf("not null\n");
        int q = fprintf(f, "%s", c);
        printf("%d", q);
    }
    else
    {
        printf("null\n");
    }
    printf("Hello, %s\n", c);
    fclose(f);
    return 0;
}

The printf returns that it's not null, and the int q returns whatever the length of the char is. Why isn't this writing to the file?

Upvotes: 0

Views: 1891

Answers (3)

Barath Ravikumar
Barath Ravikumar

Reputation: 5836

the printf returns that it's not null,

Thats because c is not null , since you have scanned your name string into it.

Why isn't this writing to the file?

The program is working fine , on my system.

-- Edit --

FILE *f = fopen("text.txt", "w+");
if (NULL == f)
  perror("error opening file\n");

By doing the error handling this way , the exact reason (in your case permissions) , would be displayed,

Upvotes: 1

Anthony
Anthony

Reputation: 12387

First off, you've declared c in local scope, so it will never be NULL. If you want to check whether or not the user entered anything, check the length of c after you've scanned in the string:

if (strlen(c) == 0) {
    ///
}

Second, check whether or not you have permission to write to the current working directory. You should be checking the return value of fopen:

if (!f) {
    fprintf(stderr, "Failed to open text.txt for writing\n");
}

Upvotes: 0

Chris Loonam
Chris Loonam

Reputation: 5745

Turns out I wasn't running with the correct permissions. Stupid mistake on my part.

Upvotes: 0

Related Questions