C语言 文件保存 【在线等】

输入文件格式为.v 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65

现在我用fgetc(fp)一个一个的读入字符,当读到.v开头的字符时,就要开始保存后面的数据,接下来的数据格式还有三位,四位,五位的,读入字符后,如何把它们组合成整数呢?请给出详细代码 谢谢

是只能用fgetc()读吧。我写了个,调试过了,
事例文件:.v 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
存在test.txt文本中。
我只读了一行,每读一个,输出一个,你根据需要改改。
#include"stdio.h"
#include"stdlib.h"
#include"math.h"
main()
{
FILE *fp;
char ch,str[5]={'\0'};//数组用来存读入的字符串例如‘50’
int i=0,j=0,n=0,data=0;//data为转换后的整型
fp=fopen("e:\\test.txt","r");
if(!fp)
{
printf("error!");
exit(1);
}
ch=fgetc(fp);
while(ch!=EOF)
{
while(ch!=' '&&ch!='\n') //以空格和换行来区分每个整数
{
if(ch>='0'&&ch<='9')
{
str[i]=ch;
str[i+1]='\0';
}
i++;
ch=fgetc(fp);
}
n=i;
if(str[0]>='0'&&str[0]<='9')
{
for(j=0;j<n;j++)
{
data+=(int)((str[j]-'0')*pow(10.0,i-1));
i--;
}
printf("%d\n",data);
}
ch=fgetc(fp);
i=0;
data=0;
}
fclose(fp);
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-03-27
fgetc(fp)一个一个的读入字符
读入的字符 不是v 继续读
读到v 则
改用
long int n=0,k;
long int x[100];
while ( fscanf(fp,"%d",&k) == 1) {
x[i] = k;
n = n + 1;
}

不用组合,读入的n 个数在 数组 x 里
第2个回答  2009-03-27
#include <stdio.h>
#include <stdlib.h>

int returnvalue(int c)
{
int temp=0;////貌似足够5位数了
while(c!=' ')
{
temp+=c-'0';
temp=temp*10;
}
return temp;
}
int main()
{
FILE *stream;
int c,value;
int a[100],i=0;

if((stream=fopen("这里改成你的文件位置", "r"))==NULL)
{
perror("cannot open the file !\n");
exit(1);
}

while((c=fgetc(stream))!=EOF && c!='v')
continue;
while((c=fgetc(stream))!=EOF)
{

value=returnvalue(c);
a[i++]=value;
}

while(i>0)
printf("%d\t", a[i--]);
return 0;
}
第3个回答  2009-03-27
你就不想一次把一行读完

char line[100];
fgets( line, 100, fp);
然后判断 line[0] == '.' && line[1] == 'v'
如果个数一定可以用sscanf(line,"%d %d %d",&d1,&d2,&d3);来读取

Get a string from a stream.

char *fgets( char *string, int n, FILE *stream );

Example

/* FGETS.C: This program uses fgets to display
* a line from a file on the screen.
*/

#include <stdio.h>

void main( void )
{
FILE *stream;
char line[100];

if( (stream = fopen( "fgets.c", "r" )) != NULL )
{
if( fgets( line, 100, stream ) == NULL)
printf( "fgets error\n" );
else
printf( "%s", line);
fclose( stream );
}
}
相似回答