简体   繁体   English

写入文件

[英]Writing into a file

I have a very simple question regarding file write. 关于文件写入,我有一个非常简单的问题。

I have this program: 我有这个程序:

char buf[20];
size_t nbytes;

strcpy(buf, "All that glitters is not gold\n");
fd= open("test_file.txt",O_WRONLY);
write(fd,buf,strlen(buf));
close(fd);

What am confused is when I open the file test_file.txt after running this program I see some characters like ^C^@^@^@^^^@ after the line "All that glitters is not": Notice that portion of the buf is not written and those characters appear instead. 令人困惑的是,当我运行该程序后打开文件test_file.txt在“所有闪烁的不是”行之后,我看到一些诸如^C^@^@^@^^^@字符:请注意,buf的这一部分未写入,而是显示那些字符。 Why is that so? 为什么会这样?

You're writing more than 19 chars in that buffer. 您在该缓冲区中写入了超过19个字符。 Once you've done that, the behavior of your program is undefined. 完成此操作后,程序的行为是不确定的。 It could do whatever it wants. 它可以做任何想做的事。

Allocate a large enough buffer. 分配足够大的缓冲区。 It has to be able to fit all the letters plus a terminating 0 if you need to be able to treat it as a C string. 如果您需要将其视为C字符串,则它必须能够容纳所有字母并加上一个终止符0

The string "All that glitters is not gold\\n" is longer than 20 characters. 字符串"All that glitters is not gold\\n"的长度超过20个字符。 I suggest you try it with a larger buffer. 我建议您尝试使用更大的缓冲区。

Actually, if you're going to do any nontrivial work in CI suggest you never ever use strcpy , as a general habit. 实际上,如果您打算在CI中进行任何不平凡的工作,则建议您永远不要使用strcpy作为一般习惯。 Use functions like strncpy which let you specify a buffer size so that it's clear you'll never overflow. 使用诸如strncpy函数,该函数可让您指定缓冲区大小,这样很显然您永远不会溢出。

libgcc strcpy Manual says: libgcc strcpy手册说:

If the destination string of a strcpy() is not large enough (that is, if the programmer was stupid or lazy, and failed to check the size before copying) then anything might happen. 如果strcpy()的目标字符串不够大(也就是说,如果程序员很笨或很懒,并且在复制之前无法检查大小),则可能会发生任何事情。 Overflowing fixed length strings is a favorite cracker technique. 固定长度的字符串溢出是最喜欢的爆破技术。

Also the strlen says strlen

The strlen() function calculates the length of the string s, not including the terminating '\\0' character. strlen()函数计算字符串s的长度,不包括结尾的'\\ 0'字符。

So i guess strlen () does not return what you expect it to return and as a result the extra characters are written 所以我猜strlen ()不会返回您期望的结果,因此会写出额外的字符

To make the thing work, you need to allocate a large enough buffer, which can hold the entire string. 为了使它正常工作,您需要分配足够大的缓冲区,该缓冲区可以容纳整个字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM