我想编写一个程序来打开一个包含数字的文本文件。 程序应创建一个新的二进制文件,其中第一个数字是整行中的数字。
我的问题是,当我想检查程序是否正确编写了数字时,数字的数量写得很好,但是其余的每一行都一样
例:
1.2222 0.2222 1111 0.111112 111111 5 3 1 9 4 4.33333 3.222 31.222 83883838 73.383883 83.344449494 12.3333 44444 322 9999.99999 7
这是文件的外观
9 1.2222 0.2222 1111 0.111112 111111 5 3 1 9 4 4 4.33333 3.222 31.222 3 83883838 73.383883 83.344449494 5 12.3333 44444 322 9999.99999 7
这就是我的样子
9 12.3333 44444 322 9999.99999 7 4 12.3333 44444 322 9999.99999 7 3 12.3333 44444 322 9999.99999 7 5 12.3333 44444 322 9999.99999 7
#include <stdio.h>
#include <stdlib.h>
#define IN 1
#define OUT 0
struct rec
{
size_t num;
char *arr;
};
int number_of_numbers(char * buffer)
{
int counter, state;
int i;
i=counter = state = OUT;
while((buffer[i]!='\n')&&(buffer[i]!=EOF))
{
if(buffer[i]==' '||buffer[i]=='\t') state = OUT;
else if(state==OUT)
{
state = IN;
counter++;
}
i++;
}
return counter;
}
int how_many_lines(char *buffer)
{
int i,counter;
i=0;
counter = 1;
while(buffer[i]!=EOF)
{
if(buffer[i]=='\n') counter++;
i++;
}
return counter;
}
int main()
{
FILE *f,*f_2;
long lSize;
char *buffer;
struct rec r;
int i;
f = fopen("f", "r");
f_2=fopen("nf", "wb");
if(!f) return 1;
fseek(f, 0, SEEK_END);
lSize = ftell(f);
rewind (f);
buffer = (char*)malloc(sizeof(char)*lSize);
r.arr = (char*)malloc(sizeof(char)*lSize);
while(fgets(buffer,lSize,f)!=NULL)
{
r.num = number_of_numbers(buffer);
r.arr = buffer;
fwrite(&r, sizeof(struct rec), 1, f_2);
}
fclose(f_2);
f_2=fopen("nf", "rb");
for(i=0; i<4; i++)
{
fread(&r,sizeof(struct rec),1,f_2);
printf("%d %s \n",r.num, r.arr);
}
fclose(f);
free(buffer);
fclose(f_2);
return 0;
}
我不知道问题出在记录上,还是您看过了,还是其他地方了
While writing a
size_t
to a file may make some sense, writing achar *
to a file doesn't really make any sense. Remember, achar *
is a fixed-length pointer that holds the address at which something is stored. What the point of writing the address at which something is stored into a file?Okay, so
buffer
always contains the address of this one block of memory that you allocated.So the value of
r.arr
is always the address of that one single block of memory. What's the point of writing the address of a block of memory to a file? And what's the point of writing the address of the very same block of memory to a file over and over? Maybe you want to try writing the contents of that buffer to the file instead?