gpt4 book ai didi

C 二进制文件与 ascii 文件

转载 作者:太空宇宙 更新时间:2023-11-04 08:30:57 24 4
gpt4 key购买 nike

所以我是 C 的新手。我需要编写一个程序,将二进制整数文件作为输入,使用 malloc 分配一个足够大的数组,然后使用 read() c 函数将每个整数存储在二进制文件中文件在数组中的相应位置。我的问题是我不知道如何区分这两者。当我打印出存储在这个分配的数组空间中的数据时,它只显示二进制数据的 Ascii 值作为一串字符。因此,例如,如果我有二进制数 0000 0001,位置 [0]-[7] 中的数组将是该二进制数中每一位的每个 ascii 值。

基本上,我试图读取每一行并将该行的二进制信息的 int 表示形式存储在 1 个数组位置中,因此与上面的示例一样,所需的结果将是:[0] - 1.我需要做一些转换算法吗?我相信有一种方法可以让 c 识别它的二进制信息,而不是 ascii,因为有两种不同的文件类型:二进制和 ASCII。任何帮助将不胜感激,提前致谢!

P.s 我只能使用这些函数调用:open、close、read、malloc、fstat、printf

else
{
fileDescriptor = open(argv[1], O_RDONLY, 0);
if (fileDescriptor == -1){
printf("File Not Found\n");
exit(1);
}
else{
if (fstat(fileDescriptor, &fileStat) < 0){
printf("Trouble pulling statistics of file\n");
exit(1);
}
else
{
numBytes = fileStat.st_size;
filePointer = (char*) malloc(numBytes);
n = read(fileDescriptor, filePointer, (numBytes * sizeof(int)));

if( n < 0 ){
printf("Problem reading the file\n");
exit(1);
}
numerator = 0;
numCount = 0;
average = 0;

while(*filePointer != NULL)
{
numerator += *filePointer;
printf("data in array: %d\n", *filePointer);
filePointer++;
numCount++;
}
average = (double) numerator / (double) numCount;
printf("Average: %f\n", average);

printf("Total Numbers: %d\n", numCount);
}
}

最佳答案

您的 read() 可能会出错,因为您尝试读取 numBytes 整数,但整数不是字节。如果您正确检查了读取的返回值,您会发现文件不是 numBytes * sizeof(int) 大。如果文件确实包含整数,而不是 ASCII 数字字符串,那么您可以按以下方式访问整数:

int *pInt= (int *)filePointer;
while (pInt < filePointer+numBytes) { printf("%d,", *pInt); pInt++;}

如果文件包含数字的 ASCII 字符串,您需要一个分隔符来表示一个数字的结束位置和下一个数字的开始位置,并且可以这样写:

char *s= filePointer;
while (s<filePointer+numBytes) {
int num= 0;
while (s<filePointer+numBytes && '0'<= *s && *s<='9') {
num= num*10 + *s-'0';
s++;
}
while (s<filePointer+numBytes && !('0'<= *s && *s<='9')) s++; // skip separator(s)
}

关于C 二进制文件与 ascii 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28391463/

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