gpt4 book ai didi

c - 如何使用低级 write() 函数将字符串写入文件?

转载 作者:行者123 更新时间:2023-11-30 19:48:16 25 4
gpt4 key购买 nike

例如,我可以使用以下命令将输入​​文件的内容写入输出文件:

char buffer[1024]; // character buffer
char userInput[1024]; // for user input
char *p;
char *q;
int n;
int input_file1; // file descriptor for file 1
int input_file2; // file descriptor for file 2
int output_file; // file descriptor for output_file

while((n = read(input_file1, buffer, sizeof(buffer))) > 0)
{
progress("entered first while loop");
if((write(output_file, buffer, n)) < 0)
{
progress("couldn't write to output within while loop 1");
perror(argv[3]);
close(input_file1);
close(input_file2);
close(output_file);
exit(1);
}
}

我还有一些用户输入:

printf("\nEnter text then hit enter: ");
q = fgets(userInput, sizeof(userInput), stdin);

我想使用 write() 将用户输入附加到同一输出文件;

我该怎么做?

-----更新----适用于

if(strcmp(argv[1], "-") == 0) // use standard-in for input file 1
{
progress("file 1 detected as \"-\": using std input");
p = fgets(userInput, sizeof(userInput), stdin);
if (write(output_file, userInput, sizeof(p)) < 0) {
progress("write from stdin to output file failed");
perror(argv[4]);
exit(1);
}
progress("wrote from stdin to output file");
}

最佳答案

只是你做了同样的事情。但您不必在第一时间关闭文件。

从用户(stdin)获取输入,然后使用write()函数将其写入文件

q = fgets(userInput, sizeof(userInput), stdin);
write(output_file, userInput, strlen(userInput));
close(output_file);

关于c - 如何使用低级 write() 函数将字符串写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19677287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com