freadステートメントを適切にフォーマットする方法を理解するのに問題があります。以下のコードは、Imが練習しているランダムなものです。基本的には、最初の配列(s)に情報を入力し、ファイルに「s」を書き込んでから、ファイルを2番目の配列(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);
}