我目前正试图创建一个二进制字节修补程序,但陷入了一个小问题。
当尝试逐字节读取输入文件并同时将这些字节写入输出文件时,换行符会以某种方式加倍。
这样的输入:

  line1
  line2
  line3

看起来像:
  line1

  line2

  line3
   

实际的程序有点复杂,但是这个抽象应该能让我知道我要做什么。
  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>

  #define SECTOR 32

  int main(int argc, char** argv) {
    FILE* input = fopen(INPUT_FILE, "r");
    FILE * output = fopen(OUTPUT_FILE, "w");
    int filesize = size of opened file...
    char buffer[16] = {0};

    int i = 0;
    while(i < filesize) {
      fseek(input, i, SEEK_SET);
      fread(buffer, sizeof(char), SECTOR, input);

      if(cmp buffer with other char array) {
        do stuff

      } else {
        i++;
        fwrite(&buffer[0], sizeof(char), 1, output);
      }
    }
    print rest of buffer to the file to have the past SECTOR-1 bytes aswell...
    fclose(input);
    fclose(output);
    return 1;
  }

最佳答案

尝试使用open、close、read和write,而不是fopen fread fwrite和fclose。你应该得到这样的东西:

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#define BUFFSIZE 32

int main(int argc, char** argv) {
    int input = open(INPUT_FILE, O_RDONLY);
    int output = open(OUTPUT_FILE, O_WRONLY | O_CREATE, S_IWUSR | S_IRUSR);
    int i = 0;
    char buffer[BUFFSIZE];


    while((i = read(input, buffer, BUFFSIZE)))  {
        if(cmp buffer with other char array) {
            do stuff
        } else {
            while (i < 0) {
                i--;
                write(output, &buffer[i], sizeof(char));
            }
        }
    }
    close(input);
    close(output);
    return 1;
}

关于c - C fread/fwrite在处理换行符时表现异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36791115/

10-11 23:14
查看更多