#include <stdio.h>
#include <stdlib.h>
#define MAXLINE 80
typedef struct Node{
char *data;
struct Node *next;
}Node;
int get_Line(FILE *fp, char s[], int lim);
Node* addNode(Node *front, char *data);
Node* fillList(Node *front, char *txtFile, int lim);
int main() {
Node *dataFront = NULL;
dataFront = fillList(dataFront,"data.txt",MAXLINE);
printf("%s\n",dataFront->data); //prints blank line
return 0;
}
int get_Line(FILE *fp, char s[], int lim){
int c, i;
for (i = 0; i < lim-1 && (c=getc(fp)) != EOF && c != '\n'; ++i)
s[i] = c;
if (c == '\n'){
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
Node* addNode(Node *front, char *data){
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if(front!= NULL)
newNode->next = front;
front = newNode;
return front;
}
Node* fillList(Node *front, char *txtFile, int lim){
FILE *fp = fopen(txtFile,"r");
char data[lim];
while(get_Line(fp,data,lim) > 0){
front = addNode(front, data);
printf("%s\n",front->data); //prints the string member of Node
//front just fine
}
printf("%s\n",front->data); //prints blank line
fclose(fp);
return front;
}
텍스트 파일에서 줄을 읽음으로써 문자열을 포함하는 노드 목록을 만듭니다. 텍스트 파일은 무엇이든 될 수 있습니다.내 노드의 String 멤버가 생성 된 후 빈 줄을 인쇄하는 이유는 무엇입니까?
print 문을 디버깅하는 데 fillList 함수에 넣습니다. 함수에서 fillList 인쇄 front-> while 루프 내의 데이터는 작동하지만 while 루프 외부에서는 빈 줄이 인쇄됩니다. 주 인쇄에서 문자열 멤버는 빈 줄을 제공합니다. 이 문제를 해결하는 데 도움이 필요해. 떨어져 내 디버깅 get_Line 및 addNode 잘 작동합니다.
편집 1 : 내 텍스트 파일 - data.txt로이 - 다음과 같은 텍스트가 포함 - txt file screenshot - 내 출력은 JPEG에서 볼 수있다 : output screenshot
프로그램의 출력은 무엇입니까? 빈 줄이 무엇을 의미하는지 정확히 알지 못합니다. 데이터 가운데, 이전, 이후에 오는 것입니까? 아니면 유일한 것이 인쇄 되었습니까? 프로그램의 결과를 포함하도록 질문을 업데이트해야합니다. –
파일의 마지막에 두 개의'\ n'을 포함하고 있지 않습니까? 또한 코드에 ** 큰 ** 문제가 있습니다. – coderredoc
'newNode-> data = strdup (data)'는 일부 UB를 수정합니다 – pm100