AALC
AALC

Reputation: 93

Printing the code of the file

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    FILE *f;
    f = fopen("my file.txt", "w");
    int n = 5;
    fprintf(f, "n equals to %d", n);
    fclose(f);
    f = fopen("my file2.txt", "w");
    char *txt = "New file";
    fwrite(txt, 1, strlen(txt), f);
    fclose(f);
    f = fopen("my file3.txt", "w");
    char *txt2 = "Hello";
    for(int i = 0; i < strlen(txt2); i++)
    {
        printf("Mouse cursor at %d.\n", ftell(f));
        fputc(txt2[i], f);
    }
    fclose(f);
    f = fopen(__FILE__, "r");
    char str[1024];
    while (!feof(f))
    {
    fscanf(f, "%s", str);
    puts(str);
    }
    putchar('\n');
    fclose(f);
    f = fopen(__FILE__, "r");
    long size = fseek(f, 0, SEEK_END);
    char *buffer = malloc(sizeof(char) * size + 1);
    fread(buffer, 1, size, f);
    puts(buffer);
    free(buffer);
    fclose(f);
    return 0;
}

Take a look in this part of the code :

f = fopen(__FILE__, "r");
long size = fseek(f, 0, SEEK_END);
char *buffer = malloc(sizeof(char) * size + 1);
fread(buffer, 1, size, f);
puts(buffer);
free(buffer);
fclose(f);

I've tried to print the code in my file and this is what I wrote to do it ^ When I try to print it with puts function it prints 3 characters : http://i61.tinypic.com/ortdvl.png

The third character is changing in each execution. Anyway to the question, I don't know why this happens can someone explain me what I did wrong ?

Upvotes: 0

Views: 90

Answers (1)

BLUEPIXY
BLUEPIXY

Reputation: 40145

fseek(f, 0, SEEK_END);
long size = ftell(f);
char *buffer = calloc(size + 1, sizeof(char));
rewind(f);
fread(buffer, 1, size, f);

Upvotes: 2

Related Questions