Thread: Verifying file existence with access function

  1. #1
    Registered User
    Join Date
    Feb 2016
    Posts
    6

    Verifying file existence with access function

    Ok so I'm new to C, this is the first time I've done anything with it. I have to create small compiler for a class, however before I get to doing that I need to check that the file that will be compiled exists, so I made a few functions to get a file path and then verify if the file exists. However, the access function seems to be telling me that my path does not exist even when it does. I'm using this on Linux. Here's my code so far:

    Code:
    #include <unistd.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main(){
    
    
    	int b_file_path;
    	char file_path[1024];
    	printf("Specify a valid file path to compile file: ");
    	
    	fgets(file_path, sizeof(file_path), stdin);
    	b_file_path = validate_file_path(file_path);
    
    
    	while(b_file_path == 0){
    		printf("Invalid file path, please specify a valid file path: ");
    		fgets(file_path, sizeof(file_path), stdin);
    		b_file_path = validate_file_path(file_path);
    	}
    	return 0;
    }
    
    
    int validate_file_path(const char* path){
    	if(access(path, F_OK)!= -1){
    		return 1;
    	}
    	return 0;
    }
    I think the problem is happening with that pointer which is an argument within "validate_file_path", but I'm not sure. I also found out that the path had a different length when I just placed it withing the access function instead of using a variable. Can someone help me out? I'm not really sure about what to check.

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Problem is actually fgets.
    The fgets() function shall read bytes from stream into the array pointed to by s, until n-1 bytes are read, or a <newline> is read and transferred to s, or an end-of-file condition is encountered. The string is then terminated with a null byte.
    Since this clearly says it will store the newline in the string results, you should expect to see "file\n" strings. You can remove the newline with string.h function strchr() like this FAQ suggests. I prefer:
    Code:
     file_path[ strcspn(file_path, "\n") ] = '\0';
    It's brief.

  3. #3
    Registered User
    Join Date
    Feb 2016
    Posts
    6
    Yes, that did it, thanks for the help.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 15
    Last Post: 12-01-2014, 12:39 PM
  2. Replies: 2
    Last Post: 03-25-2013, 01:33 AM
  3. File Existence Check :(
    By Moni in forum A Brief History of Cprogramming.com
    Replies: 1
    Last Post: 09-07-2003, 05:25 PM
  4. Checking for file existence
    By Sue Paterniti in forum C Programming
    Replies: 3
    Last Post: 05-06-2002, 02:59 AM

Tags for this Thread