1

我需要编写一个程序来反转给定二进制文件中字节的顺序。它接受命令行中的文件名。此外,它可以使用 fseek 等文件定位功能不超过固定次数。

这是我编写的代码,它没有使用固定次数:

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

int main(int argc, char** argv) {

    if (argc>2) {
        printf("Please enter a valid file name");
        return 1;
    } else {
        FILE* file;
        file=fopen(argv[1], "r");
        if (file==NULL) {
            printf("Please enter a valid file name");
            return 1;
        } else {
            FILE* fileBackUp;
            fileBackUp=fopen("c:\backupFile.txt", "w+");
            fseek(file, 0, SEEK_END);
            fseek(file, -1, SEEK_CUR);
            while (ftell(file)>=0) {
                int c= fgetc(file);
                fputc(c, fileBackUp);
                fseek(file, -2, SEEK_CUR);
            }

            fseek(fileBackUp, 0, SEEK_SET);

            int c;
            while (!feof(fileBackUp)) {
                c=fgetc(fileBackUp)
                fputc(c,file);
            }

            fclose(fileBackUp);
            fclose(file);
        }
    }
    return 1;
}

它为此使用了一个额外的文件。我当然相信有一种更短的优雅方法可以按照要求减少步骤。有什么建议么?

另一件事:似乎第一个条件总是被满足,怎么会?

4

1 回答 1

2
#include <stdio.h>

long max(long v1, long v2) { return v1 >= v2 ? v1 : v2; }
long min(long v1, long v2) { return v1 >= v2 ? v2 : v1; }
void invert_bits(char *arr, size_t size);

int main(int argc, char *argv[]) {
  size_t  read_sz;
  FILE * infile = fopen(argv[1], "r");
  fseek(infile, 0, SEEK_END);
  long file_sz = ftell(infile);
  long offset  = file_sz;
  long total_read = 0;
  long num_seeks  = 10;
  size_t  buffer_sz = (file_sz + num_seeks - 1) / num_seeks;
  char    buffer[buffer_sz];
  while (file_sz > total_read) {
    if ((offset + num_seeks - 1) / num_seeks < buffer_sz) {
      buffer_sz = offset / num_seeks;
    }
    offset = max(0, offset - buffer_sz);
    fseek(infile, offset, SEEK_SET);
    read_sz = fread(buffer, 1,
        min(buffer_sz, file_sz - total_read), infile);
    total_read += read_sz;
    invert_bits(buffer, read_sz); 
    num_seeks--;
  }
  fclose(infile);
}

void invert_bits(char *arr, size_t size) {
  size_t i;
  int j;
  for (i = size; i > 0; i--) {
    char v = arr[i - 1];
    char o = 0;
    for (j = 0; j < 8; j++) {
      o |= v & 1;
      v >>= 1;
      o <<= 1;
    }
    printf("%c", o);
  }
}
于 2012-07-17T16:13:57.183 回答