0

我编写了一个函数来从文件的指定位置读取给定数量的字节。从 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
4

2 回答 2

2

通话后

count = fread(bfr,1,n_bytes,f_ptr);

bfr不一定是字符串,因为它可能不是以 null 结尾的,因此您不能使用 打印其内容printf("string read: %s\n", bfr);或使用strlen. 您需要在循环中打印每个字符:

for (int i = 0; i < n_bytes; i++)
    printf("%c", bfr[i]);
printf("\n");

编辑

感谢@Jonathan Leffer 的评论,这看起来好多了:

printf("%.*s\n", count, bfr);
于 2013-09-27T01:58:53.617 回答
1

您没有为字符串的空终止符分配额外的字节,也不能保证存在终止符。您必须为缓冲区分配n_bytes + 1并确保最后一个字节为零。

于 2013-09-27T01:57:59.693 回答