我曾经做过类似的事情从标准输入读取内容。
char *lines[50];
char buffer[50];
while((fgets(buffer, sizeof(buffer), stdin))!=NULL) {
buffer[strlen(buffer)-1] = '\0';
lines[i] = malloc(strlen(buffer));
memcpy(lines[i++], buffer, strlen(buffer));
}
我希望使用read
系统调用来实现类似的功能。
while((nread=read(0, buffer, sizeof(buffer)))>0) {
buffer[strlen(buffer)-1] = '\0';
lines[i] = malloc(strlen(buffer));
memcpy(lines[i++], buffer, strlen(buffer));
}
将 i 重置为0,并使用 printf("%s", lines[i])
打印字符串时,我在第一种方法中得到了正确的结果,但在第二种方法中并不总是得到相应的结果。这是为什么?
另外,在使用 read 从标准输入读取时,是否需要在字符串末尾添加空字符,还是 read 会自动添加?
我将输入从包含以下内容的文件中导入:
This is test input
This is another test input
Not reading correctly, not reading correctly
使用fgets()
获取输入后打印输出会得到与输入完全相同的内容。
使用read()
获取输入后打印输出会得到以下结果:
This is test input
This is another test input
Not
reading correctly, not reading correctly
put
No
额外的注意事项:
如果我将char buffer[50]
改为更大的容量,第二种情况就能正常工作,但我不明白为什么在这一特定情况下不能正常工作。
问题似乎是当我从文件中重定向输入时,read
会读取所有的50个字符。有没有办法让read每次迭代只读取到换行符为止?它似乎在从控制台接收输入时可以做到这一点。
malloc()
时为NULL
字符分配空间,并确保在调用memcpy
之后使用NULL终止。由strlen()
返回的长度不包括NULL字符。 - DaVlines[i] = malloc(strlen(buffer)+1);memcpy(lines[i++], buffer, strlen(buffer)+1);
- BLUEPIXYbuffer
没有以NULL结尾。因此,您不能将其传递给strlen()
。 - DaVfgets()
后,buffer
末尾总是以'\0'
结尾。但它可能不会以'\n'
或'\0'
结尾。所以,使用buffer[strlen(buffer)-1] = '\0';
并不是处理潜在的'\n'
的好方法。建议使用size_t len = strlen(buffer); if (len > 0 && buf[len-1] == '\n') buf[--len] = '\0';
- chux - Reinstate Monicastrdup()
更易读,但不幸的是它不是C规范的一部分。 - chux - Reinstate Monica