如何将流转换为字符串以写入C中的日志文件?

时间:2017-05-11 19:08:37

标签: c

从套接字读取(使用epoll):

// Message to record what was input/output
char message[255]; // Leave the last four chars for '\n\0'

....  

// Determine where to read from and where to write to
read_from_socket = evlist[j].data.fd;
write_to_socket = epoll_fd_pairs[read_from_socket];

// Handle read/write
nwrite = 0;
while(nwrite != -1 && (nread = read(read_from_socket,buffer,BUFFER_SIZE)) > 0){
    total = 0;
    do{
        // Append to message buffer
        if((nwrite = write(write_to_socket,buffer+total,nread-total)) == -1){
            // TODO: Convert the byte into an ASCii character and append to the message
            // strcat(message,&nwrite);
            break;
        }
        total += nwrite;
        // Keep reading from the buffer until it is done
    }while(total < nread);
}  

我想将输入的前253个字符捕获为字符串,并将其传递给我用于写入日志文件的函数。函数调用工作正常。函数调用的参数是:

void write_to_log(char *write_sentence);

1 个答案:

答案 0 :(得分:0)

使用memcpy()buffer复制到message,然后将空终止符添加到其中,以便您可以调用write_to_log()

while(nwrite != -1 && (nread = read(read_from_socket,buffer,BUFFER_SIZE)) > 0){
    total = 0;
    memcpy(message, buffer, nread);
    message[nread] = '\n';
    message[nread+1] = '\0';
    write_to_log(message);
    do{
        // Append to message buffer
        if((nwrite = write(write_to_socket,buffer+total,nread-total)) == -1){
            // TODO: Convert the byte into an ASCii character and append to the message
            // strcat(message,&nwrite);
            break;
        }
        total += nwrite;
        // Keep reading from the buffer until it is done
    }while(total < nread);
}  

我假设BUFFER_SIZE小于253,因此总会有足够的空间。您应该声明它以便它总是足够大:

char message[BUFFER_SIZE + 2];