c - Use a variable in system() and store its output in a file -
i want store output of system() in file uses string variable.
char file[10],command[100]; printf("enter file name:\n"); fgets(file,10,stdin); sprintf(command,"lsof | grep %s >> result.txt",file); system(command); result.txt comes out empty.
after enter data
fgets(file,10,stdin); you press enter key. fgets includes newline character(\n) in buffer(file) unless input more 8 characters long.
to fix problem, need strip off newline character file problem-maker. can achieve using cool function strcspn() string.h. add following after fgets:
buffer[strcspn(buffer,"\n")] = 0; or else, use familiar strlen() function:
size_t len = strlen(buffer); if(len > 0 && buffer[len-1] == '\n') buffer[len-1] = 0; you should check if system() , fgets() successful checking return values.
Comments
Post a Comment