c - 打印文件代码

标签 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

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

最佳答案

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

关于c - 打印文件代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25651244/

相关文章:

c - 程序使用 fgets 停止读取文件

python - 打开: invalid mode or filename

c - BIOS中断_int86

c++ - 英特尔引脚 : how to detect realloc size

c - 如何将我的代码转换为使用 getchar() putchar() 而不是使用 scanf() 和 printf() 进行 I/O?

C++ 慢速读取/搜索

c - 当目录不存在时打开相对文件并显示 `open`

C 在不同的头文件中定义具有相同名称的宏?

c - 尝试更改内存地址处的值时出现段错误

python从特定位置读取二进制文件