C and files

Soldato
Joined
5 Dec 2003
Posts
2,716
Location
Glasgow
Hey i'm trying to learn C and I'm using Code Blocks IDE.

Just struggling to get this from the latest tutorial I'm following, I'm trying to write some text to a file and then read it and display it, this is what I have but isn't doing the reading/displaying bit correctly:

Code:
#include <stdio.h>
#include <stdlib.h>

FILE *output_file;

int main()
{
    char str [80];

    if ((output_file = fopen("output_file", "w")) == NULL)
        fprintf(stderr, "Cannot open %s\n", "output_file");

    fprintf(output_file, "Hi there");

    fscanf(output_file, str);
    printf(str);

    fclose(output_file);

    return 0;
}
 
A couple of things......

You havent opened the file for reading, after opening it for writing.
You need to loop through the file reading through it until EOF, which you might want to define yourself as its written.
When you print the string, you need to use %s so printf knows its a string.

Probably loads of other stuff too but that's just bits i noticed straight away, been a while since I did any file handling.
 
Back
Top Bottom