英文:
How can I print to stderr in C without using printf or puts or any function from their families?
问题
有没有一种C函数可以在不使用printf、puts或它们的任何相关函数的情况下打印到stderr?
英文:
Is there a C function to print to stderr without using printf or puts or any function from their families?
答案1
得分: 6
Using plain standard C there's only the functions you mention that can write to stdout
, stderr
, and read from stdin
.
However, those are modeled on the UNIX standard output, error and input file descriptors. So if you're on a system like Linux or macOS then you can use the write
system call to write to STDERR_FILENO
and STDOUT_FILENO
(defined in the <unistd.h>
header file).
Windows have something similar of course, with GetStdHandle
and WriteFile
.
英文:
Using plain standard C there's only the functions you mention that can write to stdout
, stderr
, and read from stdin
.
However, those are modeled on the UNIX standard output, error and input file descriptors. So if you're on a system like Linux or macOS then you can use the write
system call to write to STDERR_FILENO
and STDOUT_FILENO
(defined in the <unistd.h>
header file).
Windows have something similar of course, with GetStdHandle
and WriteFile
.
答案2
得分: 4
使用 `write` 系统调用:
```c
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[]) {
char buf[] = "你好,世界!\n";
write(2, buf, strnlen(buf,sizeof(buf)));
}
英文:
Use the write
system call:
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[]) {
char buf[] = "Hello, world!\n";
write(2, buf, strnlen(buf,sizeof(buf)));
}
答案3
得分: 3
使用stdio.h
中的fwrite
,它将数据从数组写入文件:
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
这个函数允许你指定文件。在你的情况下,可以是stderr
:
char str[] = "This is a string";
fwrite(str, sizeof(char), strlen(str), stderr);
英文:
Use fwrite
from stdio.h
, it writes data from array to a file:
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
The function allow you to specify the file. This can be stderr
in your case:
char str[] = "This is a string";
fwrite(str, sizeof(char), strlen(str), stderr);
答案4
得分: 1
你可以使用标准的 fwrite()
函数,并将 stderr
指定为最后一个参数:
#include <stdio.h>
size_t fwrite(const void *restrict ptr, size_t size, size_t nitems,
FILE *restrict stream);
另外,你可以在兼容POSIX的系统上使用 write
系统调用,并将 STDERR_FILENO
指定为第一个参数:
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
英文:
You can use the standard fwrite()
function and specify stderr
as the last argument:
#include <stdio.h>
size_t fwrite(const void *restrict ptr, size_t size, size_t nitems,
FILE *restrict stream);
Alternatively, you can use the write
syscall on POSIX-compliant systems and specify STDERR_FILENO
as the first argument:
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论