我有一个文件需要通过代码读取。该文件如下所示。文件的第一行包含一个整数,表示文件中日记条目的数量。我需要编写一个 C 程序来读取文件并将内容存储在动态分配的结构数组中。
4
12/04/2010
Interview went well I think, though was told to wear shoes.
18/04/2010
Doc advised me to concentrate on something... I forget.
03/05/2010
Was asked today if I was an art exhibit.
19/05/2010
Apparently mudcakes not made of mud, or angry wasps.
我能够 strtok() 将日、月和年存储在我的结构中,但是我一直坚持将字符串保存到我的结构中。 这是我的 strtok() 代码,
FILE* file=fopen("struct.txt","r");
if (file==NULL){
perror("Error opening file\n.");}
else {
fscanf(file,"%d",&size);
res=(Diary*)malloc(size*sizeof(Diary));
fscanf(file,"%*[^\n]");
while(fgets(day,1024,file)!= NULL){
oken=strtok(day,"/");
h[i]=atoi(oken); */h[i] is my day
oken=strtok(NULL,"/");
fre[i]=atoi(oken); */fre[i] is the month
oken=strtok(NULL,"/");
re[i]=atoi(oken); */ re[i] is the year
okena=strtok(day,"\n");
strcpy(rese[i],okena); */i had declared rese as char rese[1024]
printf("%s",okena);
i++;
}
程序无法使用 strcpy(),当我运行它时,它不断崩溃。但是,如果我删除 strcpy(),它将打印如下:
12
Interview went well I think, though was told to wear shoes.
18
Doc advised me to concentrate on something... I forget.
03
Was asked today if I was an art exhibit.
19
Apparently mudcakes not made of mud, or angry wasps.
这也不是我想存储在结构中的字符串。我陷入了如何将字符串存储到结构中的困境。我的结构是
typedef struct journal{
int day;
int month;
int year;
char entry[1024];
} Diary;
有好心人可以告诉我哪里出了问题吗?
最佳答案
以下建议代码:
- 执行所需的功能
- 为“神奇”数字赋予有意义的名称
- 将结构定义与该结构的 typedef 分开
- 更新/编辑了最新的问题详细信息
现在建议的代码:
#include <stdio.h>
#include <stdlib.h>
#define MAX_LINE_LEN 1024
struct journal
{
int day;
int month;
int year;
char entry[ MAX_LINE_LEN ];
};
typedef struct journal Diary;
int main( void )
{
FILE* file=fopen("struct.txt","r");
if ( !file )
{
perror("fopen failed");}
exit( EXIT_FAILURE );
}
// implied else, fopen successful
char line[ MAX_LINE_LEN ];
int size;
if( fgets( line, sizeof line, file ) )
{
if ( sscanf( line, "%d", size ) != 1 )
{
fprintf( stderr, "scanf for data count failed\m" );
exit( EXIT_FAILURE );
}
// implied else, input of data count successful
}
else
{
perror( "fgets for data count failed" );
exit( EXIT_FAILURE );
}
// implied else, fgets successful
Diary myDiary[ size ]; // uses VLA (variable length array feature of C
size_t i = 0;
char *token = NULL;
while( i < size && fgets( line, sizeof( line ), file) )
{
token = strtok( line, "/" );
if( token )
{
myDiary[i].day = atoi( token );
token = strtok( NULL, "/" );
if( token )
{
myDiary[i].month = atoi( token );
token = strtok( NULL, "/" );
if( token )
{
myDiary[i].year = atoi( token );
// input data directly into struct instance
fgets( myDiary[i].entry, MAX_LINE_LEN, file );
}
}
}
i++;
}
}
关于c - 如何从文件中获取替代行并将其作为字符串存储到结构中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50015872/