【发布时间】:2023-03-20 23:50:01
【问题描述】:
编辑:我现在意识到我需要问的问题是我将如何捕获 dat 文件“^M”中的回车符,如下所示抛出我的输出。
我的程序从文件中读取字符,将它们放入数组中,一旦数组已满,它就会转储输入。该文件包含我猜可能导致问题的特殊字符。我正在读取字符,然后以十六进制格式打印它们的数值,然后在下一行我想以字符形式打印相同的信息。
谁能告诉我为什么我的for 循环似乎跳来跳去?数组可能加载不正确吗?
file.dat 文件 -- 在 of 之后包含标签
This is a test of program^M
Special characters are: ^L ^H ^K
OUTPUT: -- 输出以 %x 格式打印
54 68 69 73 69 73 61 74 65 73 74 6f
66 70 72 6f 67 72 61 6d d 53 70
65 63 69 61 6c 63 68 61 72 61 63 74 65 72 73
61 72 65 3a c 8 b ffffffff 72 73
十六进制格式的输出是正确的,翻译后就是我想要和需要的输出
OUTPUT: -- 输出错误乱序
T h i s i s a t e s t o
S p o g r a m 3
e c i a l c h a r a c t e r s
a r e :
? r s
这个输出显然是错误的,让我很困惑。我不明白一个简单的for 循环是如何导致这个输出的。
代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void print_group(char array[]);
void print_space(int num);
void printbits(int bits);
int main()
{
char array[16];
char i_file;
int count = 0;
FILE *fp;
int bits = 0;
int a = 0;
fp = fopen("file.dat","r");
if( fp == NULL)
{
printf("ERROR");
}
else
{
while (!feof(fp)) /*while pointer hasnt reached end of file continue loop*/
{
array[count] = fgetc(fp);
if(count == 15 || feof(fp))
{
print_group(array);
count = -1;
printf("\n");
}
count++;
}
}
fclose(fp);
return 0;
}
void print_group(char array[])
{
int a;
int num;
for(a = 0; a <= 15; a++)
{
/*This for loop wil print the numbers that are associated with the dump
of the array.*/
if(array[a] == ' ' || array [a] == '\t' || array[a] == '\n' || array[a] == '\?')
{
printf("20 ");
}
else
printf("%x ",array[a]);
}
printf("\n");
for(a = 0; a <= 15; a++)
{
/*This for loop wil print the characters that are associated with the dump
of the array.*/
if (array[a] == ' ' || array [a] == '\t' || array[a] == '\n' || array[a] == '\?') {
printf(" ");
}
else
printf("%c ",array[a]);
}
}
void print_space(int num)
{}
【问题讨论】:
-
在两个
for循环中尝试if(array[a] <= ' ')。 -
一个提示:如果您的文件大小不是 16 字节的倍数,则从文件中读取的最后一个块的最后一部分将包含来自前一个读取块的数据。要在你
print_group(array);之后摆脱它,将数组设为 0:memset(array, 0, 16)。此外,在以十六进制打印时,请指定%02X格式说明符而不是%x,以明确它是一个十六进制字符串。 -
虽然它不太可能导致您的意外输出,但您确实错误地使用了
feof()。见stackoverflow.com/questions/5431941/…。 -
旁注:在第一个输出循环中,
if语句应该被删除。所有十六进制值都应按原样打印。 -
你的特殊字符的十六进制数是多少?
标签: c arrays special-characters fgetc