使用fscanf读取ASCII代码文件 [英] read ASCII code file using fscanf

查看:176
本文介绍了使用fscanf读取ASCII代码文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取ASCII文本文件并将其写入二进制文件.文本文件的大小不受限制.首先,我尝试在编写文本文件之前先阅读它.但是,我不断出现细分错误.我不明白是什么原因引起的.即使使用gdb,我仍然无法找出问题所在.请告知.

I am trying to read an ASCII text file and write it into binary file. The text file is unlimited in size. First, I tried to read the text file before writing it. However, I keep getting segmentation fault. I don't understand what may cause the problem. Even using gdb, I still cannot figure out the problem. Please advise.

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

typedef struct _FileData
{
int a;
double b;
char dataStr[56];
}FileData;


int main()
{

FILE * infile=fopen("output.txt", "r");
if(infile==NULL)
{
    printf("Error opening file");
    exit(1);
}

FileData **input;
int i=0;
while( fscanf(infile,"%d %f %[^\n]s",&input[i].a,&input[i].b,&input[i].dataStr)!  =NULL)
{
    printf("%d",input[i].a);
    printf("%.3f",input[i].b);
    printf("%[^\n]s",input[i].dataStr);
    i++;
}
return 0;
}

我的文本文件是

47
34.278
This is a line of text

48
23.678
This a very very long line

49
12.4569
This a very short line

50
117.906
This world is so beautiful

51
34.789
Hello world!

推荐答案

代码中的问题是您有一个指针:

The problem in your code is that you have a pointer:

FileData** input;

即使未将其初始化为指向任何有效内存,您仍在使用该指针.

You are using that pointer even though it's not been initialized to point to any valid memory.

由于您是在读取文件后立即将数据写出到stdout,因此可以使用:

Since you are writing the data out to stdout immediately after reading from the file, you can use:

FileData input;
while( fscanf(infile,"%d %lf %55[^\n]",&input.a, &input.b, input.dataStr) == 3)
                                                                      // Notice the chage here
{
    printf("%d",input.a);
    printf("%.3f",input.b);
    printf("%s\n",input.dataStr);
}

但是,我不理解对struct _FileData的需求.您可以轻松使用:

But then, I don't understand the need for struct _FileData. You can just as easily use:

int intValue;
double doubleValue;
char stringValue[56];
while( fscanf(infile,"%d %lf %55[^\n]",&intValue, &doubleValue, stringValue) == 3)
{
    printf("%d %.3f %s\n",intValue, doubleValue, stringValue);
}

这篇关于使用fscanf读取ASCII代码文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆