#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MAXLINE 512
main(int argc,char* argv[]){
int k;
for (k=0; k<=argc; k++) {
if (k%2==0) {
if (fork()==0){
FILE *fi;
FILE *fo;
int i;
fi=fopen(argv[k], "r");
fo=fopen("temp.txt","w");
if (!fi)
return;
char linie[MAXLINE],*p;
for ( ; ; ) {
p = fgets(linie, MAXLINE, fi);
if (p == NULL)
break;
linie[MAXLINE-1] = '\0';
int k=-1;
for (i = 0; i <MAXLINE; i++) {
if (linie[i]=='\n') k=i;
}
for (i = k; i >= 0; --i) {
fprintf(fo,"%c", linie[i]);
}
}
fclose(fi);
fclose(fo);
exit(1);}
}
else
{
if (fork()==0){
execl("/usr/bin/awk","awk","-f","ouk.awk",argv[k],NULL);
exit(1);
}
}
}
};
here is the ouk.awk file content
{ for (i=NF;i>=1;i--){ if(s){s=s" "$i} else{s=$i }}{print s;s=""}}
Basically what i try to do is create a number of argc processes and is the number is even to mirror the text in the file and if not to rearrange the words from every line backwards, the problem I'm facing is
fprintf(fo,"%c",line[j])
is not working and I also get an error when I try to execute the awk script
awk: can't open file > input record number 6, file > source line number 1
if I run only the awk command in terminal with the same files it works perfectly so it must have something to do with the execl command.
One more thing, I've tried the following command to rename the temp.txt int argv[k]
execl("bin/mv","temp.txt",argv[k],NULL)
but it crashes.
If anyone could help me or give me a link to a good exec c command tutorial it would be fantastic, thanks a lot
The
for
loop is going beyond the bounds of the array (which is undefined behaviour):as arrays have zero based index, running from
0
toN-1
whereN
is the number of elements in the array. The terminating condition of thefor
must bek < argc
. Additionally, the first element inargv
is the name of the program which you will want to exclude:When invoking
execl()
you need to cast the last argument to achar*
: