fopen problem

whats wrong in this code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

#include<stdio.h>

int main()
{
    char *c;
    FILE * xfile;
    xfile = fopen("del it.txt","w+");
    if(xfile!=NULL)
    {
        printf("ok");
        fputs("testing",xfile);
        fgets(c,255,xfile);
    }
    else
        perror("\nerror");
    printf("%s",c);
    fclose(xfile);
    return 0;
}


1) 'c' is a bad pointer, it doesn't point to anything. You are corrupting the heap by reading to it. Remember... pointers are pointers, they are not strings.

2) you are reading 'c' from the end of the file (ie: after your "testing" text). If you want to read the "Testing" text, you must seek to the start of the file. Look up fseek() or rewind()
Thanks for describing.
can someone show me (a example) what is the proper way of performing task like this.
Last edited on
You were close in your first attempt. You just have to change those 2 things:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int main()
{
    // char *c;  <- you don't want a pointer
    char c[256];  // <- you want a buffer
    FILE * xfile;
    xfile = fopen("del it.txt","w+");
    if(xfile!=NULL)
    {
        printf("ok");
        fputs("testing",xfile);
        rewind( xfile );  // <- go back to the start of the file
        fgets(c,255,xfile);
    }
    else
        perror("\nerror");
    printf("%s",c);
    fclose(xfile);
    return 0;
}
yap feels like i was pretty close.
thanks for helping.
Topic archived. No new replies allowed.