[英]Writing my own Cat function in C
嗨,我不知道如何在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
是“文件描述符”和“文件指針”的常規名稱)調用的函數。 您也可以指定輸出流。 因此,例如,接口:
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個字符的塊。
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()
是讀者的一項練習。 您可能會發現與C相關的Trid和真正的簡單文件復制代碼 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.