【发布时间】:2016-06-04 17:04:01
【问题描述】:
我需要读取一个文件,为此我使用函数 getline。以下是来自该网站的示例:http://crasseux.com/books/ctutorial/getline.html,为了能够打开文件,我对其进行了调整。
#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;
}
当我运行程序时,我得到一个分段错误 11,我不知道我做错了什么。提前谢谢你。
【问题讨论】:
-
始终检查您是否成功打开了文件。您没有从 get line 返回的字符串中删除换行符,因此您可能没有打开名称末尾带有换行符的文件。
-
此外,通常使用
fd表示文件描述符(int类型),fp表示文件指针(流——FILE *类型)。
标签: c segmentation-fault getline