read ASCII code file using fscanf

2019-06-05 16:42发布

问题:

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.

Code:

# 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;
}

My text file is

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!

回答1:

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.

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);
}

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);
}


标签: c ascii scanf