超过时间限制(计数二进制文件中的ASCII代码数)
每当我提交此代码时,我总是会遇到时间限制。有任何解决代码的建议吗?
这是一个问题:
计算二进制文件中ASCII代码的数量。 输入一个2位十六进制的数字,计算二进制文件A.DAT中的字节数量有多少个字节,其值完全等于十六进制的数字,统计结果必须以“%d \ n”格式写入文本中。文件b.txt。 例如: 令A.DAT包含以下内容(已转换为显示为显示的十六进制格式):
0x01 0x02 0x03 0x41 0x42 0x43 0x43 0x0d 0x0a 0xff F 0xfe 0xfe 0xfd 0x01 0x01 0x02 0x03 0x80 0x7f 0x0d 0x0d 0x0d 0x0a
###输入和输出示例:###
输入:
01
,输出:2
(因为文件中有2 0x01。)
输入:
ff
,输出:1
(因为文件中有1 0xff。)
这是代码:
#include <stdlib.h>
main(){
FILE *in,*out;
int a[100];
int b,n=0,count=0,i;
int *p=a;
in=fopen("a.dat","rb");
out=fopen("b.txt","wb");
while (fscanf(in,"%x",p++)!=EOF){
n++;
}
scanf("%x",&b);
for (i=0;i<n;i++){
if(b==a[i]){
count++;
}
}
fprintf(out,"%d\n",count);
fclose(out);
fclose(in);
return 0;
}
everytime I submit this code, I always encounter time limit exceeded. Any suggestion to fix the code?
this is the question:
Count the number of ASCII codes in a binary file.
Enter a 2-digit hexadecimal number, count how many bytes in the binary file a.dat and whose value is exactly equal to the hexadecimal number, the statistical result must be written to the text in the format of "%d\n" in file b.txt.
E.g:
Let a.dat contain the following content (which has been converted to hexadecimal format for display):
0x01 0x02 0x03 0x41 0x42 0x43 0x0D 0x0A 0xFF 0xFE 0xFD 0x01 0x02 0x03 0x80 0x7F 0x0D 0x0A
###Input and output example:###
enter:
01
, output:2
(Because there are 2 0x01 in the file.)
enter:
FF
, output:1
(Because there is 1 0xFF in the file.)
this is the code:
#include <stdlib.h>
main(){
FILE *in,*out;
int a[100];
int b,n=0,count=0,i;
int *p=a;
in=fopen("a.dat","rb");
out=fopen("b.txt","wb");
while (fscanf(in,"%x",p++)!=EOF){
n++;
}
scanf("%x",&b);
for (i=0;i<n;i++){
if(b==a[i]){
count++;
}
}
fprintf(out,"%d\n",count);
fclose(out);
fclose(in);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
目前尚不清楚数据是ASCII还是二进制。如果是ASCII,则不应使用
“ RB”
。我假设数据是原始的二进制文件。首先,使用
%x
读取原始二进制数据,并将其存储在int
中,只有在您通过字节解析int
字节时才能使用。否则,您将一次在具有32位int
的系统上一次读取4个字节,而不是8个数字,而不是2个。现在,让不是通过阅读4来使事物复杂化4一个字节一次,因为这将是一个更高级的话题。为了改进性能,您可以存储文件的实际数据,而是存储出现的频率:
这样,您只需要迭代一次数据即可。
It's not really clear if the data is ASCII or binary. In case it is ASCII, you shouldn't be using
"rb"
. I'm assuming the data is raw binary.First of all, reading raw binary data with
%x
and storing it in anint
will only work if you parse thatint
byte by byte. Otherwise you'll read 4 bytes at a time on a system with 32 bitint
and that's 8 hex digits, not 2. For now, lets not complicate things by reading 4 bytes at a time since that would be a more advanced topic.As a performance improvement, instead of storing the actual data of the file, you could store how frequently it appears:
This way you only need to iterate over the data once.