我正在尝试编写一个TCP服务器,客户端可以使用它来浏览服务器的目录.除此之外,如果是常规文件,我想发送目录的大小.文件的大小保存在"stat"结构下的size_t变量中.我在这做这个:
char *fullName /* The path to the file *. /** * Some code here */ struct stat buffer; lstat(fullName, &buffer)
所以现在buffer.st_size包含文件的大小.现在我想写()它到监听套接字,但显然我必须以某种方式将其转换为字符串.我知道这可以通过按位右移(>>)运算符以某种方式完成,但对我来说似乎太痛苦了.你能帮帮我吗(即使其他那些按位运算符也没办法)?
顺便说一句,这不适合学校或smth ......
PS:我在Linux上运行它.
您可以使用函数sprintf()
-family的成员将"something"转换为"string".
#define _POSIX_C_SOURCE 200112L #include <stdio.h> #include <unistd.h> #include <string.h> int main(void) { size_t s = 123456789; char str[256] = ""; /* In fact not necessary as snprintf() adds the 0-terminator. */ snprintf(str, sizeof str, "%zu", s); fputs(stdout, "The size is '"); fflush(stdout); write(fileno(stdout), str, strlen(str)); fputs(stdout, "'.\n"); return 0; }
打印出来:
The size is '123456789'.