[英]I am having trouble compiling and running my C program. What are the commands?
[英]I having difficulty reading the file in my program. Am I using the for loop correctly to read the file?
我正在嘗試以十六進制和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;
}
}
風向標建議使用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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.