简体   繁体   English

我如何知道字符串是否以空字符结尾?

[英]How do I know if a string is null terminated?

I am using fgetc to read a string from a file.我正在使用 fgetc 从文件中读取字符串。 As i dont know how long the string will be i need to reallocate space for the array that should hold the data.因为我不知道字符串有多长,所以我需要为应该保存数据的数组重新分配空间。 For that I need to know when the current array is full.为此,我需要知道当前数组何时已满。 I am not quite sure if the char array is null terminated after reading a character.我不太确定 char 数组在读取一个字符后是否以 null 结尾。 So for example i have an array of size 8 and fgetc is going to give me the 9th char.例如,我有一个大小为 8 的数组,fgetc 将给我第 9 个字符。 Is the size of the array now 8 or 9?现在数组的大小是 8 还是 9? (8 chars + \\0 or only the 8 chars). (8 个字符 + \\0 或仅 8 个字符)。 Is there a way to test it?有没有办法测试它? And if there is no \\0.如果没有\\0。 Do I need to add it by myself to the char array when i finished reading in the string?当我读完字符串时,我需要自己将它添加到 char 数组中吗?

You need to keep track of both the current size of the buffer, and the position where you add characters.您需要跟踪缓冲区的当前大小以及添加字符的位置。 then if the position is equal to the size you need to increase the buffer.那么如果位置等于您需要增加缓冲区的大小。 The actual size should be +1 to accommodate the terminating \\0 character, which you must always add after the last character read.实际大小应为+1以容纳终止的\\0字符,您必须始终在读取的最后一个字符之后添加该字符。

since fgetc reads a one character per call, to get size of a string, you should check read character to be a \\0 or EOF reached.由于 fgetc 每次调用读取一个字符,要获取字符串的大小,您应该检查读取的字符是否达到了 \\0 或 EOF。 if you see a \\0 byte, you should copy all the bytes including \\0.如果您看到 \\0 字节,则应复制包括 \\0 在内的所有字节。 if EOF is reached without a \\0 and if character counter is > 0, you should add a \\0 yourself.如果在没有 \\0 的情况下到达 EOF 并且字符计数器 > 0,则您应该自己添加 \\0。

When you use fgetc you are building the memory which holds the string byte by byte, so you need to have your memory allocation be total string length + 1 because you want the extra byte for the termination character '\\0'.当您使用 fgetc 时,您正在构建一个逐字节保存字符串的内存,因此您需要将内存分配设为总字符串长度 + 1,因为您需要额外的字节作为终止字符 '\\0'。

The functions that work with "string" are really looking at a collections of bytes ending with '\\0'.使用“字符串”的函数实际上是在查看以 '\\0' 结尾的字节集合。 So for example "Hello World" is stored as 'H' 'e' 'l' 'l' 'o' 'W' 'o' 'r' 'l' 'd' '\\0' in memory;例如,“Hello World”在内存中存储为 'H' 'e' 'l' 'l' 'o' 'W' 'o' 'r' 'l' 'd' '\\0'; and that's how functions know when to STOP processing a string.这就是函数知道何时停止处理字符串的方式。

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

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