The program works well. It verifies if an argument is a file or a directory and it returns 1 or 2. However, strcmp
doesn't work and I don't know why.
Here is my code:
#DEFINE N 100
int main(int argc,char* argv[]) {
FILE *fp;
char cmd[N];
char result[N];
int i;
for(i=1;i<argc;i++){
pipe(c2p);
if (fork()==0){
//Running the shell script
sprintf(cmd,"/home/flory/os/verif.sh %s", argv[i]);
fp = popen(cmd, "r");
fgets(result, N, fp);
pclose(fp);
printf("%s",result);
if (strcmp(result,"1")==0){
//DO SOMETHING
}
}
The variable x
does not have a value yet.
Did you mean the following?
if (strcmp(result,"1")==0){
//DO SOMETHING
}
Apart from variable confusion in your question, please notice what happens with the trailing newline when reading a line of text. From linux man page fgets(3):
fgets() reads in at most one less than size characters from stream and
stores them into the buffer pointed to by s. Reading stops after an
EOF or a newline. If a newline is read, it is stored into the buffer.
A '\0' is stored after the last character in the buffer.
I wrote a small program somewhat like yours:
#include <stdio.h>
main()
{
FILE *fp;
char bigbuf[10*1024];
fp = popen("/bin/echo hello world", "r");
fgets(bigbuf, sizeof bigbuf, fp);
printf("length of bigbuf: %d\nlength of \"hello world\": %d\n", strlen(bigbuf), strlen("hello world"));
exit(0);
}
Running it, I get the following output:
length of bigbuf: 12
length of "hello world": 11
result
has a terminating newline character since it has been read by fgets()
, therefore, it would contain "1\\n"
(or possibly "1\\r\\n"
, though that's unlikely), which is different from "1"
.
You can delete the newline like this:
char *p;
if((p=strchr(result,'\n'))!=0) *p=0;
If your input contains CR you can remove them the same way.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.