更新时间:2023-11-07 11:01:40
以下建议的代码:
stderr
stderr
现在,建议的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ROW_LEN 1024
#define MAX_LINES 50
#define MAX_QUESTION_LEN 255
#define MAX_ANSWER_LEN 255
void readfromfile( void ); // func prototype
char data[ MAX_ROW_LEN ]; // a row from the file
//Fragebezogen
char id[ MAX_LINES ][5]; // question nr
char frageinhalt[ MAX_LINES ][ MAX_QUESTION_LEN ]; // the question itself (later smth like "capital of germany?"
char antw1[ MAX_LINES ][ MAX_ANSWER_LEN ]; // the first answer to the question
char antw2[ MAX_LINES ][ MAX_ANSWER_LEN ]; // second answ
int main( void )
{
readfromfile();
printf("\nFrageinhalt: %s Antw1: %s Antw2: %s\n",
frageinhalt[1],
antw1[1],
antw2[1]);
return 0;
}
void readfromfile()
{
FILE *datei_ptr;
char delimiter[] = ",;#";
char *token;
datei_ptr = fopen("test.txt", "r");
if ( !datei_ptr )
{
perror( "fopen failed" );
exit( EXIT_FAILURE );
}
int lineCounter = 0;
while( lineCounter < MAX_LINES && fgets (data, sizeof( data ), datei_ptr) )
{
puts(data);
printf("###############################\n");
token = strtok(data, delimiter);
if ( token )
{
printf("Abschnitt gefunden: %s\n", token);
strncpy( id[ lineCounter ], token, 5 );
token = strtok(NULL, delimiter);
if( token )
{
strncpy( frageinhalt[ lineCounter ], token, MAX_QUESTION_LEN );
token = strtok( NULL, delimiter );
if( token )
{
strncpy( antw1[ lineCounter ], token, MAX_ANSWER_LEN );
token = strtok( NULL, delimiter );
if( token )
{
strncpy( antw2[ lineCounter ], token, MAX_ANSWER_LEN );
}
}
}
}
printf("###############################\n");
lineCounter++;
}
fclose(datei_ptr);
}