简体   繁体   中英

read ASCII code file using fscanf

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM