파일을 읽어야하고 getline 함수를 사용해야합니다. 다음은이 웹 사이트의 한 예입니다 : 파일을 열 수있게하기 위해 내가 조정 한 http://crasseux.com/books/ctutorial/getline.html.C에서 세그먼트 오류가 발생합니다.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int bytes_read;
unsigned long nbytes = 100;
char *my_string;
char *filename;
char *line;
FILE *fd = NULL;
puts ("enter filename");
filename = (char *) malloc (nbytes + 1);
bytes_read = getline (&filename, &nbytes, stdin);
fd = fopen(filename, "r");
bytes_read = getline (&line, &nbytes, fd);
puts (line);
puts ("Please enter a line of text.");
/* These 2 lines are the heart of the program. */
my_string = (char *) malloc (nbytes + 1);
bytes_read = getline (&my_string, &nbytes, stdin);
if (bytes_read == -1)
{
puts ("ERROR!");
}
else
{
puts ("You typed:");
puts (my_string);
}
return 0;
}
그리고 프로그램을 실행할 때 Segmentation 오류 11이 발생하고 내가 무엇을 잘못하고 있는지 알지 못합니다. 미리 감사드립니다.
파일을 성공적으로 열 었는지 항상 확인하십시오. get 줄에서 반환 된 문자열에서 줄 바꿈을 제거하지 않았으므로 이름 끝에 줄 바꿈이있는 파일을 열지 않았을 것입니다. –
또한, 파일 디스크립터 (int 형)에'fd'를 사용하고 파일 포인터 ('FILE *'형)에 대해'fp'를 사용하는 것이 일반적입니다. –