gpt4 book ai didi

C编程读取多行并暂停,直到按下键盘上的任意键

转载 作者:太空宇宙 更新时间:2023-11-04 03:11:16 26 4
gpt4 key购买 nike

我是 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");

}

And output should be like Sample

最佳答案

您需要将读取和打印逻辑包围在循环中。

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 continue\n");
getchar();
} while(read>0);

关于C编程读取多行并暂停,直到按下键盘上的任意键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56162923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com