fread的奇怪行为从main调用时函数的行为不同,从其他函数调用时函数的行为也不同

时间:2013-09-27 01:47:25

标签: c pointers main fread

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

2 个答案:

答案 0 :(得分:2)

通话后

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

bfr不一定是字符串,因为它可能不会以空值终止,因此您无法使用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);

答案 1 :(得分:1)

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