gpt4 book ai didi

c - 如何传递字符串以及文件供C中的open函数使用?

转载 作者:行者123 更新时间:2023-11-30 14:38:12 25 4
gpt4 key购买 nike

我有一个函数,它以文件名作为输入,并执行“打开”和“读取”调用来执行某些操作。该文件名是通过命令行参数接收的。现在,我试图使这个函数变得通用,以便它也可以接收字符串并执行相同的操作。以其他方式,我直接将文件内容作为字符串传递。

我不知道如何将字符串数据流式传输到“open”函数。另外,请注意,我被限制使用 open 函数来读取文件。

我尝试使用“管道”功能将数据流式传输到打开功能,但没有成功。

int sopen(char *s) {
int p[2], ret;
int fd=-1;
int len = strlen(s);

if (pipe(p) != 0) {
fprintf(stderr, "Error in creating pipe");
return -1;
}

if ((fd = open(p[0], O_RDONLY)) < 0) {
fprintf(stderr, "Error in open");
close(p[0]);
close(p[1]);
return -1;
}

ret = write(p[1], s, len);
if (ret != len) {
fprintf(stderr, "Error in writing to pipe");
close(p[1]);
close(fd);
return -1;

}
close(p[1]);

return fd;
}

我期望一个文件描述符,以便 open 函数可以使用它,但它返回 -1。

最佳答案

正如其他人所说,pipe()函数返回两个已经可以使用的描述符。这意味着,pipe() 已经为您打开它们。否则无法保证这些相互连接。

请记住,您有责任关闭它们!

您的整个解决方案应该类似于下面的伪代码:

main
variable: fileDescriptor

detect if command line contains a filename, or file content
if it was a filename
fileDecriptor = openFile(some arguments...)
if it was a filecontent
fileDecriptor = openAndFillPipe(some other arguments...)

doWhetever(fileDescriptor) // here's the 'operations' on the 'file'

close(fileDescriptor) // whatever we got, we need to clean it up


openFile(filename)
// simply: any file-opening will do
descriptor = open(filename, ...)


openAndFillPipe(filecontent)
// first, make a pipe: two connected descriptors
int pairOfDescriptors[2];
pipe(pairOfDescriptors);

// [0] is for reading, [1] is for writing
write(pairOfDescriptors[1], filecontent, ...) // write as if to a file

close(pairOfDescriptors[1]) // we DONT need the 'write' side anymore

descriptor = pairOfDescriptors[0] // return the 'read' as if it was a file

关于c - 如何传递字符串以及文件供C中的open函数使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56730367/

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