我编写了一个函数来从文件中从指定位置读取给定数量的字节。当从 main 调用时,这将按预期工作。但是当它从其他函数调用时,而这些函数又从main调用,它也读取某些额外的垃圾字符(其中一些是不可打印的)。
请解释正在发生的事情以及如何防止它。代码和相应的输出如下所示:
编辑:最终目标是计算此数据的哈希值,创建一个数据包(数据+哈希),并通过TCP套接字将其发送到网络中的另一个节点。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * read_from_file(char * filename, int offset, int n_bytes)
{
printf("Inside read functionn");
printf("offset: %dn",offset);
printf("n_bytes: %dn",n_bytes);
char * bfr;
FILE * f_ptr;
int count;
f_ptr = fopen (filename,"r");
if(f_ptr==NULL)
{
printf("File not foundn");
exit(1);
}
//Set the offset position
fseek(f_ptr, offset , SEEK_SET);
//memory aloocation
bfr = malloc (sizeof(char)*n_bytes);
if (bfr == NULL)
{
printf("Memory allocation problemn");
exit (2);
}
count = fread(bfr,1,n_bytes,f_ptr);
printf("no. of characters read from file: %dn",count);
printf("string read: %sn", bfr);
printf("Length of string read: %zdn",strlen(bfr));
if (count != n_bytes)
{
printf("Error in reading the file");
exit(1);
}
// Close the file
fclose (f_ptr);
printf("Exiting read functionnn");
return bfr;
}
int send_file()//nc_args_t * nc_args)
{
printf("Inside send_filen");
char * data;
data = malloc (10);
data = read_from_file("alphabet.txt", 0, 10);
printf("Length of data: %dn",strlen(data));
printf("Data Read: %sn", data);
}
int main()
{
char * data;
data = read_from_file("alphabet.txt", 0, 10);
printf("Length of data: %zdn",strlen(data));
printf("Data Read: %sn", data);
printf("nCalling send_filen");
send_file();
}
输出
Inside read function
offset: 0
n_bytes: 10
no. of characters read from file: 10
string read: ABCDEFGHIJ
Length of string read: 10
Exiting read function
Length of data: 10
Data Read: ABCDEFGHIJ
Calling send_file
Inside send_file
Inside read function
offset: 0
n_bytes: 10
no. of characters read from file: 10
string read: ABCDEFGHIJLsE
Length of string read: 14
Exiting read function
Length of data: 14
Data Read: ABCDEFGHIJLsE
通话后
count = fread(bfr,1,n_bytes,f_ptr);
bfr
不一定是字符串,因为它可能不以 null 结尾,因此您无法使用 printf("string read: %sn", bfr);
打印其内容或使用 strlen
获取其长度。您需要在循环中打印每个字符:
for (int i = 0; i < n_bytes; i++)
printf("%c", bfr[i]);
printf("n");
编辑
感谢您@Jonathan Leffer的评论,这看起来好多了:
printf("%.*sn", count, bfr);
您不会为字符串的 null 终止符分配额外的字节,也不能保证终止符存在。 必须为缓冲区分配n_bytes + 1
,并确保最后一个字节为零。