打印文件的代码

时间:2014-09-03 18:29:53

标签: c 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;
}

看一下代码的这一部分:

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);

我已经尝试在我的文件中打印代码,这就是我写的内容^ 当我尝试使用puts函数打印它时,它会打印3个字符: http://i61.tinypic.com/ortdvl.png

第三个字符在每次执行中都在变化。 无论如何,我不知道为什么会发生这种情况有人能解释我做错了什么?

1 个答案:

答案 0 :(得分:2)

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