我正在实现一个基本的getline()函数,用于读取文件内容并将其写入终端,然而
这完全可以用
#include<stdlib.h>
int main(int argc , char *argv[])
{
FILE *fp = fopen(argv[argc-1],"r");
if(fp == NULL)
{
printf("error : can't open file");
exit(1);
}
char *buf = NULL;
size_t linelen = 0;
size_t linecapp = 0;
while((linelen = getline(&buf,&linecapp,fp)) !=-1)
{
fwrite(buf,linelen,1,stdout);
}
fclose(fp);
return 0;
}
但这
#include<stdio.h>
#include<stdlib.h>
int main(int argc , char *argv[])
{
FILE *fp = fopen(argv[argc-1],"r");
if(fp == NULL)
{
printf("error : can't open file");
exit(1);
}
char *buf = NULL;
size_t linelen = 0;
size_t linecapp = 0;
while((linelen = getline(&buf,&linecapp,fp)) >= 0)
{
fwrite(buf,linelen,1,stdout);
}
fclose(fp);
return 0;
}
正在给出分段错误.
唯一不同的是
while循环中的!= -1 and >= 0
是一样的.
What I tried
printf("%zu\n", linelen);
在我的while循环中,我得到了这个
<\n\n>
116
hello world this is a test file to bes used for the purpose of learning basics of unix sys calls and c programming
77
this is just an extra line to elongate the file followed by more extra lines
55
for example this is a line used in elongating the file
22
this is another line
141
this line contain special characters like œ∑´®†¥¨ˆøπåß∂ƒ©˙∆˚¬¬¬…≈ç√∫˜µ≤≥÷¡™£¢∞§¶•ªº–
52
this line contain some numbers 1 2 3 5 7 4 6 8 9 10
18446744073709551615
his line contain some numbers 1 2 3 5 7 4 6 8 9 10
?¥¨ˆøπåß∂ƒ©˙∆˚¬¬¬…≈ç√∫˜µ≤≥÷¡™£¢∞§¶•ªº–
Xjm??ͫ?????@|m? ?5?r?@?@:?#??Zm@?` `@?`?`?Zm???#? ??#????#?????#?@?`X???\/var/folders/l5/h45_tftn3w18ws8vshrpxlsr0000gn/T//private/tmp/com.apple.launchd.pIOsn5DWl2/Listeners0?``SSH_AUTH_SOCK??`??????????????????`??`P ?b??,?,?8Zm@??Xm? ??`(?`?`HOME?Xm?D<?B`38?`P`PATH?Xm?81??` ?`?`TMPDIR?Xm?83?`??!???c?8???W&???ǀ?G???w+???C???????`??`@``?```?Z??`ԥ`???`???`???`?@`?a??\_?x?`?`?`?Z????^??\_?x?`????`?pm?? ??
m ??um?? ?x ?h
m?
?@
m?? ??
m?`
??
zsh: segmentation fault ./getlinefunc ../../sampletextfile.txt
为了进行比较,这里是原始样本文本文件
hello world this is a test file to be used for the purpose of learning basics of unix sys calls and c programming
this is just an extra line to elongate the file followed by more extra lines
for example this is a line used in elongating the file
this is another line
this line contain special characters like œ∑´®†¥¨ˆøπåß∂ƒ©˙∆˚¬¬¬…≈ç√∫˜µ≤≥÷¡™£¢∞§¶•ªº–
this line contain some numbers 1 2 3 5 7 4 6 8 9 10
它最终为linelen带来了非常大的价值.