【问题标题】:read ASCII code file using fscanf使用 fscanf 读取 ASCII 码文件
【发布时间】:2014-11-05 04:32:46
【问题描述】:

我正在尝试读取 ASCII 文本文件并将其写入二进制文件。文本文件的大小不受限制。首先,我尝试在写入之前读取文本文件。但是,我不断遇到分段错误。我不明白什么可能导致问题。即使使用 gdb,我仍然无法找出问题所在。请指教。

代码:

# 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!

【问题讨论】:

  • 你永远不会初始化input
  • 不是答案,但为什么printf("%[^\n]s"... 而不是普通的printf("%s"...
  • 为什么将输入声明为指向 FileData 指针的指针?
  • 这里FileData **input;需要在使用fscanf之前使用malloc给input分配内存。
  • @nIcE cOw fscanf(infile, "%s", someString); 不会扫描“This is a line of text”,而只会扫描“This”。

标签: c ascii scanf


【解决方案1】:

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

FileData** input;

您正在使用该指针,即使它没有被初始化为指向任何有效内存。

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

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 的必要性。您也可以轻松使用:

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

【讨论】:

  • 感谢您的建议。 struct _FileData 是赋值的一部分。我无法更改它。
  • @SunnyTrinh 您是否获得了正确的浮点值。我在这里将所有浮点值都设为 0.000。
  • 看来我们需要在 fscanf 函数中使用 %lf 才能正常工作。
  • @Sarwan 建议从"%d %f %[^\n]s" 中删除s。 --> "%d%lf %55[^\n]".
  • 最好使用%55[^\n] 以确保datastr 不会溢出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多