嗨,我不知道如何在 C 中模拟我自己的 Cat 函数,我知道在没有设置参数时它是如何工作的,我已经知道了,但我的问题是当我试图打开一个文件然后打印它自己时...
到目前为止我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int main(int argc, char* argv[])
{
char *a1 = (char*) malloc (sizeof(char));
int sz, fd,cont=0, cont1=0;
char *b1 = (char*) malloc (sizeof(char));
//char *a2 = (char*) malloc (sizeof(char));
char * a2;
char *b2 = (char*) malloc (sizeof(char));
// NO PARAMETERS
while (argc == 1){
sz=read(0, a1, 1);
b1[cont]=a1[0];
if(b1[cont]=='\n'){
write(1,b1,cont);
write(1,"\n",1);
b1=NULL;
}
cont=cont+1;
b1=(char*) realloc(b1, sizeof(char)*cont);
}
// 1 PARAMETER (FILE) /*Here is the problem*/
if (argc > 1){
fd=open(argv[1],O_RDONLY);
a2=fgetc(fd);
while (a2 != EOF){
b2[cont1]=a2;
cont1=cont1+1;
b2=(char*) realloc (b2, sizeof(char)*cont1+1);
a2=fgetc(fd);
}
write(1,b2,cont);
b2=NULL;
close(fd);
}
return 0;
}
我该怎么办?
最佳答案
如果您使用 open()
和 close()
, 你不能使用 fgetc()
.您需要使用 fopen()
和 fclose()
能够使用 fgetc()
.
无论哪种方式,您都需要一个可以使用标准输入(拼写为 0
或 stdin
)或打开的文件( fd
或 fp
是"file"的常规名称)调用的函数描述符”和“文件指针”)。您也可以指定输出流。因此,例如,接口(interface):
int cat_fd(int ifd, int ofd);
int cat_fp(FILE *ifp, FILE *ofp);
您的主程序然后使用标准输入和标准输出或打开的文件和标准输出调用您选择的函数。
此外,您还有:
char *a1 = (char*) malloc (sizeof(char));
忽略类型转换,这是一种昂贵的写作方式:
char a1[1];
您的循环一次读取一个字符。这对于来自 <stdio.h>
的文件流是可以的,但如果您使用的是文件描述符,则对性能不利。您应该一次阅读 4096 个字符的 block 。
int cat_fd(int ifd, int ofd)
{
char buffer[4096];
ssize_t nbytes;
while ((nbytes = read(ifd, buffer, sizeof(buffer))) > 0)
{
if (write(ofd, buffer, nbytes) != nbytes)
return -1;
}
return (nbytes < 0) ? -1 : 0;
}
你不需要动态内存分配;这只会让您感到困惑并在程序中浪费时间。 main()
中的代码函数看起来更像:
if (argc == 1)
{
if (cat_fd(0, 1) != 0)
fprintf(stderr, "failed to copy standard input\n");
}
else
{
for (int i = 1; i < argc; i++)
{
int fd = open(argv[i], O_RDONLY);
if (fd < 0)
fprintf(stderr, "failed to open %s for reading\n", argv[i]);
else
{
if (cat_fd(fd, 1) != 0)
fprintf(stderr, "failed to copy %d to standard output\n", argv[i]);
close(fd);
}
}
}
重写以使用 cat_fp()
是给读者的练习。你可能会发现 Tried and true simple file copying code in C相关。
关于c - 用 C 编写我自己的 Cat 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30064937/