Hi i don't know how to simulate my own Cat function in C, i know how it works when no arguments are set and i already get it, but my problem is when i tried to open a file and then print itself...
my code until now:
#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;
}
What am i supposed to do ?
o2.c:34:3: warning: passing argument 1 of ‘fgetc’ makes pointer from integer without a cast [enabled by default] a2=fgetc(fd); ^ ejercicio_evaluado2.c:34:5: warning: assignment makes pointer from integer without a cast [enabled by default] a2=fgetc(fd); ^ ejercicio_evaluado2.c:35:13: warning: comparison between pointer and integer [enabled by default] while (a2 != EOF){
– Pernodopen
succeeded.fgetc
returns anint
, not achar*
and expects aFILE*
as the parameter, not anint
, usefopen
or don't usefgetc
. – Caseaseread
- in case of EOF, returned size will be 0. (The same applies for the no-argument case, where you are incorrectly ignoring the value ofsz
.) You can either usefopen
andfgetc
(orfgets
, etc.) oropen
andread
. You cannot useopen
and then callfgetc
on the file descriptor -fgetc
is a higher-level function that expects to receive a different kind of object. – Compulsive