2

我在弄清楚如何正确格式化 fread 语句时遇到了一些麻烦。下面的代码只是我练习的一些随机的东西。基本上它将信息填充到第一个数组(s)中,将“s”写入文件,然后将文件读入第二个数组(s2)。但是,我似乎无法以不出错或不返回垃圾的方式格式化 fread 语句。数组是 char 数据类型,因为如果我的理解是正确的,char 使用的内存比其他数据类型少。该实践代码的最终应用是用于数据压缩项目。

#include<stdio.h>
#include<string.h>

FILE *fp;
//file pointer

char s[56];
//first string

char s2[56];
//target string for the fread

int n=0;
//counting variable

int m=0;

int main (void)
{
    fp=fopen("test.bin", "w+");
    //open a file for reading and writing


    strcpy(s, "101010001101010");
    //input for the string

    for(n=0;n<56;n++)
    {
        if(s[n]==1)
            m=n;
        else if(s[n]==0)
            m=n;
    }
    printf("%d\n", m);
    //the above for loop finds how many elements in 's' are filled with 1's and 0's
    for(n=0;n<m;n++)
    {
        printf("%c", s[n]);
    }
    //for loop to print 's'


    fwrite(s, m, 1, fp);
    //writes 's' to the first file
    s2=fread(&s2, m, 1, fp);
    //an attempt to use fread...

    printf("\n\ns2\n\n");
    for(n=0;n<m;n++)
    {
        printf("%c", s2[n]);
    }
    printf("\n");
    //for loop to print 's2'
    fclose(fp);

    printf("\n\n");
    printf("press any number to close program\n");
    scanf("%d", &m);
}
4

2 回答 2

5

FILE 结构在文件中具有隐式查找位置。你从那个寻找位置读写。如果您想阅读您所写的内容,您需要通过调用将查找位置更改回文件的开头fseek()。实际上,对于一个打开读写的文件,fseek()在读写切换时必须调用。

于 2013-01-16T15:28:13.137 回答
1

函数的返回值fread是类型size_t。它是成功读取的元素数。(参考:http ://www.cplusplus.com/reference/cstdio/fread/ )

不要将其分配给 s2。只需使用fread(&s2, m, 1, fp);

于 2013-01-16T15:28:58.760 回答