我在C编程中非常新。我希望我能解释我的问题。我正在尝试开发一个程序来读取binary
文件并转换为ASCII
模式。没有任何问题。但是我要做的是询问用户,他/她想阅读多少行(例如20行(,然后仅显示二进制文件中的20行,然后询问用户按任何键继续。按下任何键后,然后再次显示该文件的下一个20行,依此类推。
我尝试使用getch()
和getchar()
,但仅适用于一行。
我以下代码可能有助于正确解释。请帮助我。预先感谢您。
#include<conio.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void header(); //Title function declaration
int main(int argc, char *argv[])
{
FILE *fp; // File pointer declaration
int i, j;
unsigned char buffer[17]; // Trying to get value for 16 bites each
fp = fopen(argv[1], "rb");
if (argc == 1) { // Condition for if user didnt specify file name
/* Assume that argv[0] is the program name */
printf("usage: %s, <file_name>", argv[0]);
return 0;
}
if (fp == NULL) { // condition if there is no file
fprintf(stderr, "File Open error (%s) , error = %d", argv[1], errno);
exit(1);
}
else
{
header(); // Calling function header
int read = 0;
int address = 0;
while ((read = fread(buffer, 1, 16, fp)) > 0)
{
printf("%08X", address);
printf(" ");
address += 16;
for (i = 0; i < read; i++)
{
if (i == 8) {
if (buffer[i] != NULL)
printf("-");
}
else {
printf(" ");
}
printf("%02X", buffer[i]);
}
int space = 16 - read;
if (space != 0) {
for (int x = 0; x < space; x++) {
int y = read + (x - buffer[x]);
printf(" ");
}
}
printf(" ");
for (j = 0; j < read; j++)
{
if (buffer[j] == NULL) {
printf(".");
}
if (isprint(buffer[j])) {
printf("%c", buffer[j]);
//fflush(stdin);
}
else {
if (buffer[j] != NULL) {
printf(".");
}
}
}
printf("n");
}
}
fclose(fp);
return 0;
}
void header() {
printf("ADDRESS ");
for (int i = 0X00; i <= 0X0F; i++)
{
if (i == 8) {
printf("-");
}
else
{
printf(" ");
}
printf("%02X", i);
}
printf(" 0123456789ABCDEF n");
printf("----------------------------------------------------------------------------n");
}
和输出应该像 样品
您需要包围阅读和打印逻辑。
int read = 0;
int address = 0;
int numLines = 0;
printf("How many lines you want to print?");
scanf("%d", &numLines);
do {
for(int i = 0; i<numLines; i++)
{
if ((read = fread(buffer, 1, 16, fp)) > 0)
{
....... //your printing logic here
}
}
/*Flush input stream in case n left out*/
int c;
while ((c = getchar()) != 'n' && c != EOF) { }
printf("press Any key to continuen");
getchar();
} while(read>0);