我编写了一个函数来从文件的指定位置读取给定数量的字节。从 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 function\n");
printf("offset: %d\n",offset);
printf("n_bytes: %d\n",n_bytes);
char * bfr;
FILE * f_ptr;
int count;
f_ptr = fopen (filename,"r");
if(f_ptr==NULL)
{
printf("File not found\n");
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 problem\n");
exit (2);
}
count = fread(bfr,1,n_bytes,f_ptr);
printf("no. of characters read from file: %d\n",count);
printf("string read: %s\n", bfr);
printf("Length of string read: %zd\n",strlen(bfr));
if (count != n_bytes)
{
printf("Error in reading the file");
exit(1);
}
// Close the file
fclose (f_ptr);
printf("Exiting read function\n\n");
return bfr;
}
int send_file()//nc_args_t * nc_args)
{
printf("Inside send_file\n");
char * data;
data = malloc (10);
data = read_from_file("alphabet.txt", 0, 10);
printf("Length of data: %d\n",strlen(data));
printf("Data Read: %s\n", data);
}
int main()
{
char * data;
data = read_from_file("alphabet.txt", 0, 10);
printf("Length of data: %zd\n",strlen(data));
printf("Data Read: %s\n", data);
printf("\nCalling send_file\n");
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