我在程序中读取文件时遇到了困难。我是否正确使用for循环来读取文件?

时间:2016-09-22 17:20:20

标签: c

我正在尝试以十六进制和ASCII格式打印文件的内容。我想我正在使用for循环错误地读取文件。输出的代码应与此类似

00000000  3C 54 49 54  4C 45 3E 43  50 45 34 39  32 20 52 65  <TITLE>CPE492 Re
00000010  73 6F 75 72  63 65 73 3C  2F 54 49 54  4C 45 3E 0A  sources</TITLE>.

代码:

#include <stdio.h>

int main() {

    FILE * file;
    file = fopen( "BinaryFile.txt" , "r");
    if (file == NULL) {
        printf("Error: %m\n");
    }
    char textFile[1000];
    for(int j=0;j<1000; j++) {

        fgets(textFile, 1000, file);
        char binaryNumber[1000],hexaDecimal[1000];
        int temp;
        long int i=0,j=0;

        while(binaryNumber[i]){
            binaryNumber[i] = binaryNumber[i] -48;
            ++i;
        }

        --i;
        while(i-2>=0){
            temp =  binaryNumber[i-3] *8 + binaryNumber[i-2] *4 +  binaryNumber[i-1] *2 + binaryNumber[i] ;
            if(temp > 9)
                hexaDecimal[j++] = temp + 55;
            else
                hexaDecimal[j++] = temp + 48;
            i=i-4;
        }

        if(i ==1)
            hexaDecimal[j] = binaryNumber[i-1] *2 + binaryNumber[i] + 48 ;
        else if(i==0)
            hexaDecimal[j] =  binaryNumber[i] + 48 ;
        else
            --j;

        printf("Equivalent hexadecimal value: ");

        while(j>=0){
            printf("%c",hexaDecimal[j--]);
        }
        return 0;
    }

    }

1 个答案:

答案 0 :(得分:0)

天气风向标建议使用fread 我建议使用argv[1]作为文件名 类似于以下内容

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

int main(int argc, char *argv[]) {
    if(argc != 2){
        printf("Usage: %s filename\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    FILE *file = fopen( argv[1] , "rb");
    if (file == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }
    size_t n;
    unsigned no = 0;
    unsigned char buffer[16];

    while(n = fread(buffer, 1, 16, file)){
        printf("%08X", no);
        for(size_t i = 0; i < n; ++i){
            if(i % 4 == 0)
                putchar(' ');
            printf(" %02X", buffer[i]);
        }
        for(size_t i = n; i < 16; ++i){
            if(i % 4 == 0)
                putchar(' ');
            printf(" %2s", "");
        }
        fputs("  ", stdout);
        for(size_t i = 0; i < n; ++i){
            putchar(isprint(buffer[i]) ? buffer[i] : '.');
        }
        puts("");
        no += 16;
    }
    fclose(file);
    return 0;
}