[英]Reading strings with read() system call in C
I need to implement a C function 我需要实现一个C函数
ssize_t readString(int filedes, char* buf, ssize_t max);
that reads a string from file associated with file descriptor 'filedes' , into buffer 'buf' and returns the number of bytes read. 从与文件描述符'filedes'相关的文件中读取一个字符串到缓冲区'buf'中,并返回读取的字节数。 The 'max' variable isn't necessary.
不需要'max'变量。
In other words I want to use 换句话说我想用
readString(fileDescriptor, buf);
the same way I would use 用同样的方式
fscanf(inputFile, "%s", buf);
Below I refer what I have done so far, but it doesn't work well at all times. 下面我将介绍我到目前为止所做的事情,但这并不总是有效。 Do you have any suggestions for my code?
您对我的代码有什么建议吗? Can you suggest a better implementation of this function?
您能否建议更好地实现此功能?
Thanks 谢谢
ssize_t readString(int filedes, char* buf){
char *temp;
int n = sizeof(buf)/sizeof(char); int i;
ssize_t rbytes = 0; /* bytes read */
size_t cbyte = sizeof(char);
/* check if file is empty */
if (read(filedes, temp, cbyte) < 1)
return 0;
/* eat spaces */
while ( (*temp == ' ') || (*temp == '\n') || (*temp == '\t') )
if (read(filedes, temp, cbyte) < 1)
return 0;
/* read string */
for (i=0; i<n-1; i++){
buf[i] = *temp;
rbytes++;
/* check if file is over */
if (read(filedes, temp, cbyte) < 1)
return rbytes;
/* check if string is over */
if ( (*temp == ' ') || (*temp == '\n') || (*temp == '\t') )
break;
}
buf[++i] = '\0';
return rbytes;
}
ssize_t readString(int filedes, char* buf){
char *temp;
int n = sizeof(buf)/sizeof(char); int i;
I think you misunderstand what sizeof
does. 我认为您误会了
sizeof
功能。 It figures out the size of the thing you ask it to figure out the size of. 它计算出您要求它计算出的东西的大小。 In this case, that's
buf
, which is a char *
. 在这种情况下,这是
buf
,它是一个char *
。 So you're basically asking it how many bytes a pointer to a character takes. 因此,您基本上是在问一个字符指针占用多少字节。 Presumably, you want the size of the buffer.
想必您想要缓冲区的大小。 So your function needs that as an additional parameter.
因此,您的函数需要将其作为附加参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.