0

I am trying to remove a file from the current working directory. When I try to make it print "Invalid file" when file is not found, it throws me a segmentation fault. This snippet is part of a bigger program.

Code:

printf("\nEnter your current password:\t"); scanf("%s",temp2); comp2 = strcmp(password,temp2); file = (char*)malloc(100 * sizeof(char)); if(comp2 == 0) { int value; printf("\nEnter the file name:\t"); scanf("%s",file); sprintf(cmd,"rm -i %s",file); value=system(cmd); if(value == -1) printf("\nFile not Found. Exiting Program"); } else printf("\nThe password is incorrect. Please try again."); break; 

Any help please? Thanks in advance.

6
  • 1
    Where is cmd allocated? Also, rm -i is an interactive command but you're not an interactive process. Also, C has an unlink call so you don't have to use system... Commented Mar 26, 2014 at 1:43
  • 2
    How about using remove (caveats) or unlink? Commented Mar 26, 2014 at 1:44
  • 1
    Executing rm in a subprocess isn't a good way to delete files from a C program. It's open to all sorts of potential problems, such as an unusual $PATH causing rm not to be found, or spaces in the filename causing rm to misunderstand what file you're trying to delete. Use a system call, such as unlink, to make your own program delete the file instead of running some other program to delete it. Commented Mar 26, 2014 at 1:53
  • 1
    you read a password of unbounded length into a fixed buffer? That cries buffer overflow. Same for reading the filename. Is cmd big enough to accomodate file and the command? Even if it is, follow Wyzards advice. Finally, i suggest you signal successful completion somehow too... Commented Mar 26, 2014 at 2:09
  • How did you declare variable cmd? Commented Mar 26, 2014 at 4:25

2 Answers 2

1

You can use the remove function

remove(file_name); 
Sign up to request clarification or add additional context in comments.

Comments

1

Use remove(path) - it removes file or directory.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.