Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C linux中的read调用是否在EOF处添加了换行符?_C_Linux_Newline_Eof - Fatal编程技术网

C linux中的read调用是否在EOF处添加了换行符?

C linux中的read调用是否在EOF处添加了换行符?,c,linux,newline,eof,C,Linux,Newline,Eof,为什么linux中文件的read()在EOF处添加换行符,即使该文件实际上没有换行符 我的文件数据是: 1hello2hello3hello4hello5hello6hello7hello8hello9hello10hello11hello12hello13hello14hello15hello 在读取“15hello”中的最后一个“o”后,我对该文件的read()调用应达到EOF。我使用以下方法: while( (n = read(fd2, src, read_size-1)) != 0)

为什么linux中文件的read()在EOF处添加换行符,即使该文件实际上没有换行符

我的文件数据是:

1hello2hello3hello4hello5hello6hello7hello8hello9hello10hello11hello12hello13hello14hello15hello
在读取“15hello”中的最后一个“o”后,我对该文件的read()调用应达到EOF。我使用以下方法:

while( (n = read(fd2, src, read_size-1)) != 0) // read_size = 21
{
    //... some code
    printf("%s",src);
    //... some code
}
其中fd2是文件的描述符。在最后一个循环中,n是17,我的src[16]='\n'。那么,linux中的read调用是否在EOF添加了一个换行符

linux中的read调用是否在EOF处添加了换行符

没有

您的输入文件中可能有一个终止换行符-大多数格式良好的文本文件都有,因此可以将多个文件连接在一起,而无需同时运行行

您还可能遇到已在缓冲区中的离群换行符,因为
read()
不会使用
NUL
字符终止数据读取以创建实际的C样式字符串。我猜你的代码也没有,否则你会发布它。这意味着你的

printf("%s",src);
很可能是未定义的行为。

为什么linux中文件的read()在EOF处添加换行符,即使该文件实际上没有换行符
read()
系统调用不会在文件末尾添加任何新行

您遇到这种行为的原因可能是您使用
vi
命令创建了文本文件,请注意,如果您使用
vi
创建了文件,则会添加默认的新行

通过使用
vi
创建一个空文本文件,然后在该文件上运行
wc
命令,您可以在系统上验证这一点

此外,如果您知道文件大小(使用
stat()
system call查找大小),则可以使用
read()
system call一次读取所有文件数据,并且可以避免
while
循环

这个

改为

struct stat var;
stat(filename, &var); /* check the retuen value of stat()..having all file info now */
off_t size = var.st_size;
现在您有了文件的
size
,创建一个等于
size
的动态或堆栈数组,并从文件中读取数据

char *ptr = malloc(size + 1);
现在一次读取所有数据,就像

read(fd,ptr,size);/*now ptr having all file contents */

最后,工作完成后,不要忘记通过调用
free(ptr)

释放
ptr
,您可能应该在问题中显示
cat-n data.txt
的输出。另请参见,
hd
将以十六进制显示字符代码,从而显示文件中的确切内容。(有些人更喜欢
od
--八进制转储)。
man-hd
了解更多信息。@jww:$cat-n testdoc2.txt 11hello2hello3hello4hello5hello6hello7hello8hello9hello10hello11hello12hello13hello14hello15@rici:它在末尾显示一个点。对于点,它给出了十六进制值0a | lo14hello15。|末尾的
0a
是一个换行符。所以它一直都在档案里<代码>人工ascii如果需要表格。
stat(fd,&var)是错误的。这应该是
fstat(fd,&var)
int size=var.st\u size
也是错误的,因为Agree@AndrewHenle让我修改它。read()没有在末尾添加“\0”。即使我没有添加'\0',我看到当我分配char str[30]时,默认情况下前30个字符都是'\0'值。使用C++代码创建测试文件,该代码不在结尾打印“\n”。我在gedit中打开文件进行小编辑,但我和gedit都不会向其中添加任何换行符。我也很困惑,因为read()的手册页没有提到新行。这里的问题是关于新行(而不是“\0”)。@Jayanth您误解了Andrew Henle的评论。他这样说是因为
read
并没有添加
'\0'
,而是添加
printf(“%s”
需要一个,
printf
可能正在读取
read
读取的
n
字符的末尾,并在
src
数组右侧的随机内存中的某个地方找到一个散乱的
\n
字符。@Jayanth,你还说了“当我分配char str[30],默认情况下,前30个字符都是“\0”值”,但根据您分配str的方式和位置,必须保证0-fill;您可能意外获得该结果。
read(fd,ptr,size);/*now ptr having all file contents */