#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
typedef struct student{
char name[25];
float marks;
}student_t;
int size = 0;
int capacity = 2;
char filename[30];
#define LINE_SIZE 128
void print(student_t **arr){
for (int i = 0; i < size; i++){
printf("%d: %s, %f\n", i+1, arr[i]->name, arr[i]->marks);
}
}
int create_table_entry(student_t **arr, int *size, int *capacity){
//printf("%d",size);
if( *size == *capacity) {
*capacity = *capacity * 2;
*arr = realloc (*arr, *capacity * sizeof(student_t));
}
return 0;
}
void add_record(student_t **arr, char *name, char *marks){
create_table_entry(arr,&size ,&capacity);
strcpy(arr[size]->name, name);
arr[size]->marks = atof(marks);
size++;
//print(arr);
}
int get_token(char *line, char fields[][30], char *delim) {
int token_cnt = 0;
char *token = strtok(line , delim);
while(token != NULL) {
// check if there is more than two tokens
if(token_cnt >= 2) {
return 3;
}
//printf("%s\n", token);
strcpy(fields[token_cnt++], token);
// update token
token = strtok(NULL, delim);
}
return token_cnt;
}
static void sort_data(){
// printf("reading the file ...........");
FILE *fileOpen = fopen( filename , "r");
if (fileOpen == NULL){
fprintf(stderr, "Error in opening input file. Filename = %s, Error = %s\n", filename, strerror(errno));
exit (-1);
}
char line[LINE_SIZE];
char fields [2][30];
student_t *arr;
arr = malloc(capacity * sizeof(student_t));
while(fgets(line, LINE_SIZE, fileOpen) != NULL){
int no_of_token = get_token(line, fields, ",");
// printf("%d\n",no_of_token);
if(no_of_token != 2){
//printf(" number of fields is not 2 for entry %d",j);
continue;
}
add_record(&arr,fields[0],fields[1]);
//printf("%s \n %s",fields[0],fields[1]);
}
print(&arr);
free(arr);
}
void check_argument(int argc,char *argv[]){
int count =0;
for(int i=1; i<argc; i++){
if(strstr("-f",argv[i])){
sprintf(filename,"%s",argv[i+1]);
count++;
}
}
if(count>1||count<1){
printf("invalid format");
}
//printf("%s\n",filename);
}
int main(int argc, char *argv[]){
check_argument(argc, argv);
sort_data();
return 0;
}
위의 프로그램에서 내가하고 싶은 것은 (.csv) 파일을 한 줄씩 읽은 다음 해당 줄을 get_token 함수에 전달하여 토큰을 생성할 수 있도록 하고 내가 원하는 2개의 필드가 있는 줄만 원합니다. add_record 함수에 전달하고 동적 구조체 배열을 생성하여 정렬하고 다른 파일에 저장할 수 있도록 2개의 토큰 값을 가져옵니다. 하지만 파일에서 학생 레코드의 값을 얻지 못하고 실행하면 코어 덤프가 표시됩니다. c로 프로그래밍하는 것이 처음이므로 이 문제를 도와주세요. 또한 내 코드가 눈을 아프게 했다면 죄송합니다.
이 부분
void print(student_t **arr){
for (int i = 0; i < size; i++){
printf("%d: %s, %f\n", i+1, arr[i]->name, arr[i]->marks);
}
}
문제가 있습니다. 당신은 포인터-to-student_t에 대한 포인터를 전달하므로 색인을 생성할 때 그것이 포인터-to-student_t의 배열이라고 예상합니다. 그러나 실제로는 student_t의 배열이 있습니다.
노력하다:
void print(student_t *arr){
for (int i = 0; i < size; i++){
printf("%d: %s, %f\n", i+1, arr[i].name, arr[i].marks);
}
}
다음과 같이 호출하십시오. print(arr);
편집 : @kaylum의 의견에서 지적했듯이 여기에 동일한 문제가 있습니다.
strcpy(arr[size]->name, name);
arr[size]->marks = atof(marks);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다