使用 fread 在 C 中读取 ASCII 文件

Reading an ASCII file in C using fread

我正在尝试使用 fread() 读入一个 ascii 文件,对每个字节进行按位补码并通过加 3 对其进行编码并写入新文件。到目前为止,这是我所拥有的,但我一直 运行 遇到错误,有人知道如何解决这个问题吗?我 运行 遇到的错误是按位补码,我的 input.txt 文件中有当前值 AB1 C23 DEF 但这是写入 output.txt 文件的内容 AB1 C23 德国

所以不确定如何修复它。

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

int main() {
    // declare variables
    FILE *ip = NULL;
    FILE *op = NULL;
    unsigned char *b;
    int i;

    // open files
    ip = fopen("input.txt", "r");
    op = fopen("out.txt", "w+");

    char out;
    while(fread(b,sizeof(b), 1, ip) == 1) {
        out = ~(&b); 
        //printf("%s\n", b);
        fwrite(out, sizeof(b), 1, op);
    }

    if (feof(ip)) {
        fclose(ip);
        fclose(op);
    }
}

您的代码中存在一些问题,但可能导致程序崩溃的问题是您对变量 b.

的使用
unsigned char *b;

b前的星号表示变量b是指向char的指针,即char的内存地址。但是,您从未实际分配内存中 b 指向的位置。

while(fread(b,sizeof(b), 1, ip) == 1) {
    out = ~(&b); 
}

注意这里你传入 b 作为 fread 应该写入的指针,这是正确的,但是你使用 sizeof(b),这不是大小char 的大小,但指向 char 的指针的大小(通常分别为 8 位和 64 位)。然后,在 while 循环中,您引用 &b,它是 b 的内存地址,即指向指针的指针,这不是您想要操作的。要让您的程序运行,您需要将 b 声明为 char 并从那里开始运行。您的代码应如下所示:

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

int main() {
    // declare variables
    FILE *ip = NULL;
    FILE *op = NULL;
    char b;
    int i;

    // open files
    ip = fopen("input.txt", "r");
    op = fopen("out.txt", "w+");

    while(fread(&b, sizeof(b), 1, ip) == 1) {
        b = ~b; 
        printf("%c\n", b);
        fwrite(&b, sizeof(b), 1, op);
    }

    fclose(ip);
    fclose(op);
}