Executable fails to open files when double clicked - c

I have a C file called fileTest.c, which simply contains this:
#include <stdio.h>
int main()
{
FILE* file = fopen("test.txt","r");
if (file == NULL) {
printf("file failed to open\n");
}
fclose(file);
return 0;
}
In the same directory, I have the test.txt file, which is empty.
I compile like so: gcc -Wall -std=gnu99 fileTest.c -o fileTest
Everything works perfectly (nothing is printed) if I run the resultant executable in the command line with ./fileTest, but when I try to run the executable by double clicking the exec file, I get "file failed to open". I'm using macOS High Sierra 10.13.3. Why is this happening?

You need to provide the full path of the file "test.txt".
I tested it on the macOS High Sierra 10.13.2 with g++ 5.5.0. This is the output

the following proposed code:
outputs the current working directory path
handles any error on the call to fopen()
outputs a message if the call to fopen() is successful
handles any error on the call to getcwd()
and now the proposed code:
#include <stdio.h>
#include <unistd.h>
int main( void )
{
char pathName[1024];
if( !getcwd( pathName, sizeof( pathName ) )
{
perror( "getcwd failed" );
exit( EXIT_FAILURE );
}
// implied else, getcwd successful
printf( "current working Directory: %s\n", pathName );
FILE* file = fopen("test.txt","r");
if (file == NULL)
{
perror("file failed to open\n");
exit( EXIT_FAILURE );
}
// implied else, fopen successful
printf( "call to fopen successful\n" );
fclose(file);
return 0;
}
However, it does not effect your question about why double clicking the executable does not cause the executable to be executed.

Related

C Prog fprintf not generating output

I've written the following code below and ran it without errors on both xcode and vscode. However, I wasn't able to get any output filename.txt. It wasn't in any of my folders.
Appreciate if anyone could help.
#include <stdio.h>
#include <string.h>
int main() {
FILE *fp=NULL;
fp = fopen("filename.txt","w+");
if (fp!= NULL){
fprintf(fp,"%s %d","Hello",555);
}
fclose(fp);
return 0;
}
ran it without errors
fclose(NULL) is undefined behavior (UB), so it is not clear that there was no error when file failed to open.
Print something in both cases of opening success/failure - and with a '\n'. Useful to add error info.
Robust code checks all I/O operations.
#include <stdio.h>
#include <string.h>
int main() {
const char *filename = "filename.txt";
FILE *fp = fopen(filename,"w+");
if (fp == NULL) {
fprintf(stderr, "Unable to open <%s>\n", filename);
perror("fopen()");
} else {
printf("Success opening <%s>\n", filename);
if (fprintf(fp,"%s %d","Hello", 555) < 0) {
fprintf(stderr, "Print failure with <%s>\n", filename);
perror("fprintf()");
}
if (fclose(fp) == EOF) {
fprintf(stderr, "Failed to close <%s>\n", filename);
perror("fclose()");
}
}
return 0;
}
I've also tried the perror method and it shows filename.txt: Permission denied. Later.
Check if filename.txt is read-only, or in use by another application (editor?), or other permission limitations.
If the file wasn't successfully opened, then the code does nothing (apart from closing a null FILE-pointer, which is undefined). You should use perror() to indicate why it couldn't be opened:
const char *const filename = "filename.txt";
FILE *const fp = fopen(filename, "w+");
if (!fp) {
perror(filename);
return EXIT_FAILURE;
}
fprintf(fp, "%s %d", "Hello", 555);
There's a good chance that you have an existing filename.txt that isn't writable by you, or you are in a directory where you can't create a new file, but we'll need the error message to actually determine why it wasn't opened.
Alternatively, you're running in a different working directory to where you thought you were - that's something you should investigate (perhaps produce some logging to stderr to indicate where the file is being created).
I ran your code and it works just finecheck this image
but, how are you compiling it and did you remember to run the a.out/execution?

create file in c without duplicates [duplicate]

Is there a better way than simply trying to open the file?
int exists(const char *fname)
{
FILE *file;
if ((file = fopen(fname, "r")))
{
fclose(file);
return 1;
}
return 0;
}
Look up the access() function, found in unistd.h. You can replace your function with
if (access(fname, F_OK) == 0) {
// file exists
} else {
// file doesn't exist
}
Under Windows (VC) unistd.h does not exist. To make it work it is necessary to define:
#ifdef WIN32
#include <io.h>
#define F_OK 0
#define access _access
#endif
You can also use R_OK, W_OK, and X_OK in place of F_OK to check for read permission, write permission, and execute permission (respectively) rather than existence, and you can OR any of them together (i.e. check for both read and write permission using R_OK|W_OK)
Update: Note that on Windows, you can't use W_OK to reliably test for write permission, since the access function does not take DACLs into account. access( fname, W_OK ) may return 0 (success) because the file does not have the read-only attribute set, but you still may not have permission to write to the file.
Use stat like this:
#include <sys/stat.h> // stat
#include <stdbool.h> // bool type
bool file_exists (char *filename) {
struct stat buffer;
return (stat (filename, &buffer) == 0);
}
and call it like this:
#include <stdio.h> // printf
int main(int ac, char **av) {
if (ac != 2)
return 1;
if (file_exists(av[1]))
printf("%s exists\n", av[1]);
else
printf("%s does not exist\n", av[1]);
return 0;
}
Usually when you want to check if a file exists, it's because you want to create that file if it doesn't. Graeme Perrow's answer is good if you don't want to create that file, but it's vulnerable to a race condition if you do: another process could create the file in between you checking if it exists, and you actually opening it to write to it. (Don't laugh... this could have bad security implications if the file created was a symlink!)
If you want to check for existence and create the file if it doesn't exist, atomically so that there are no race conditions, then use this:
#include <fcntl.h>
#include <errno.h>
fd = open(pathname, O_CREAT | O_WRONLY | O_EXCL, S_IRUSR | S_IWUSR);
if (fd < 0) {
/* failure */
if (errno == EEXIST) {
/* the file already existed */
...
}
} else {
/* now you can use the file */
}
Yes. Use stat(). See the man page forstat(2).
stat() will fail if the file doesn't exist, otherwise most likely succeed. If it does exist, but you have no read access to the directory where it exists, it will also fail, but in that case any method will fail (how can you inspect the content of a directory you may not see according to access rights? Simply, you can't).
Oh, as someone else mentioned, you can also use access(). However I prefer stat(), as if the file exists it will immediately get me lots of useful information (when was it last updated, how big is it, owner and/or group that owns the file, access permissions, and so on).
FILE *file;
if((file = fopen("sample.txt","r"))!=NULL)
{
// file exists
fclose(file);
}
else
{
//File not found, no memory leak since 'file' == NULL
//fclose(file) would cause an error
}
You can use realpath() function.
resolved_file = realpath(file_path, NULL);
if (!resolved_keyfile) {
/*File dosn't exists*/
perror(keyfile);
return -1;
}
I think that access() function, which is found in unistd.h is a good choice for Linux (you can use stat too).
You can Use it like this:
#include <stdio.h>
#include <stdlib.h>
#include<unistd.h>
void fileCheck(const char *fileName);
int main (void) {
char *fileName = "/etc/sudoers";
fileCheck(fileName);
return 0;
}
void fileCheck(const char *fileName){
if(!access(fileName, F_OK )){
printf("The File %s\t was Found\n",fileName);
}else{
printf("The File %s\t not Found\n",fileName);
}
if(!access(fileName, R_OK )){
printf("The File %s\t can be read\n",fileName);
}else{
printf("The File %s\t cannot be read\n",fileName);
}
if(!access( fileName, W_OK )){
printf("The File %s\t it can be Edited\n",fileName);
}else{
printf("The File %s\t it cannot be Edited\n",fileName);
}
if(!access( fileName, X_OK )){
printf("The File %s\t is an Executable\n",fileName);
}else{
printf("The File %s\t is not an Executable\n",fileName);
}
}
And you get the following Output:
The File /etc/sudoers was Found
The File /etc/sudoers cannot be read
The File /etc/sudoers it cannot be Edited
The File /etc/sudoers is not an Executable
From the Visual C++ help, I'd tend to go with
/* ACCESS.C: This example uses _access to check the
* file named "ACCESS.C" to see if it exists and if
* writing is allowed.
*/
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
void main( void )
{
/* Check for existence */
if( (_access( "ACCESS.C", 0 )) != -1 )
{
printf( "File ACCESS.C exists\n" );
/* Check for write permission */
if( (_access( "ACCESS.C", 2 )) != -1 )
printf( "File ACCESS.C has write permission\n" );
}
}
Also worth noting mode values of _access(const char *path,int mode):
00: Existence only
02: Write permission
04: Read permission
06: Read and write permission
As your fopen could fail in situations where the file existed but could not be opened as requested.
Edit: Just read Mecki's post. stat() does look like a neater way to go. Ho hum.

C File Name with multiple periods

Simple question.
When I try to open a file with the name text.txt it works properly.
However if I rename the file to text.cir.txt it gives me ERROR.
What can I do to fix it?
FILE *fd;
char nome_fich[] = "text.cir.txt";
int x;
fd = fopen("text.cir.txt", "r");
if (fd == NULL)
{
printf("ERROR");
}
else
{
while ((x = fgetc(fd)) != EOF)
{
printf("%c", x);
}
fclose(fd);
}
the following proposed code:
cleanly compiles
performs the desired functionality
properly checks for and handles errors
and now, the proposed code:
#include <stdio.h> // FILE, fopen(), perror(), printf()
#include <stdlib.h> // exit(), EXIT_FAILURE
int main( void )
{
FILE *fd = fopen( "text.cir.txt", "r" );
if ( !fd )
{
perror( "fopen failed" );
exit( EXIT_FAILURE );
}
// implied else, fopen successful
int x;
while ((x = fgetc(fd)) != EOF)
{
printf("%c", x);
}
fclose(fd);
}
when run against any .txt file, it performs the desired operation.
Note: I'm running Linux version 18.04

a program that takes one command line argument and outputs the contents of the file to standard out.

I was assigned a program to write that uses file system calls to take a command line argument(assuming you pass in a text file address) and return the contents of said file. I have this code so far, but can't seem to figure out why my compiler is giving me errors in terms of recognizing the text-file passed as an argument, along with printing the information received from the file. Any sort of assistance/help is greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
int main(int argc, char *argv[]){
int FP;
ssize_t bytes;
char buffer [100];
if(argc == 1){
FP = open(argv[1], O_RDONLY);
printf("Program name is : %s", argv[0])
bytes = read(FP, buffer,sizeof(buffer) -1);
printf("%s", bytes);
close(FP);
}
return 0;
}
the following proposed code:
incorporates the comments to the question
implements the desired functionality
proper checks for errors
documents why the header files are being included. In general, if you cannot state why a header file is being included, then don't include it. (the compiler will then tell you if you actually need that header file, and why
when compiling always enable the warnings, then fix those warnings. (for gcc, at a minimum use: -Wall -Wextra -pedantic -Wconversion -std=gnu11 )
and now, the proposed code.
#include <stdio.h> // fopen(), perror(), fgets(), fprintf(), printf(), FILE
#include <stdlib.h> // exit(), EXIT_FAILURE
#define MAX_INPUT_LEN 100
int main(int argc, char *argv[])
{
FILE *fp;
char buffer [ MAX_INPUT_LEN ];
if(argc != 2)
{
fprintf( stderr, "USAGE: %s fileName\n", argv[0] );
exit( EXIT_FAILURE );
}
// implied else, correct number of command line parameters
printf( "Program name is : %s", argv[0] );
printf( "file to read: %s\n", argv[1] );
fp = fopen( argv[1], "r" );
if( NULL == fp )
{
perror( "fopen failed" );
exit( EXIT_FAILURE );
}
// implied else, fopen successful
while( NULL != fgets( buffer, sizeof buffer, fp ) )
{
printf( "%s", buffer );
}
fclose( fp );
return 0;
}

C way to check if file exists [duplicate]

Is there a better way than simply trying to open the file?
int exists(const char *fname)
{
FILE *file;
if ((file = fopen(fname, "r")))
{
fclose(file);
return 1;
}
return 0;
}
Look up the access() function, found in unistd.h. You can replace your function with
if (access(fname, F_OK) == 0) {
// file exists
} else {
// file doesn't exist
}
Under Windows (VC) unistd.h does not exist. To make it work it is necessary to define:
#ifdef WIN32
#include <io.h>
#define F_OK 0
#define access _access
#endif
You can also use R_OK, W_OK, and X_OK in place of F_OK to check for read permission, write permission, and execute permission (respectively) rather than existence, and you can OR any of them together (i.e. check for both read and write permission using R_OK|W_OK)
Update: Note that on Windows, you can't use W_OK to reliably test for write permission, since the access function does not take DACLs into account. access( fname, W_OK ) may return 0 (success) because the file does not have the read-only attribute set, but you still may not have permission to write to the file.
Use stat like this:
#include <sys/stat.h> // stat
#include <stdbool.h> // bool type
bool file_exists (char *filename) {
struct stat buffer;
return (stat (filename, &buffer) == 0);
}
and call it like this:
#include <stdio.h> // printf
int main(int ac, char **av) {
if (ac != 2)
return 1;
if (file_exists(av[1]))
printf("%s exists\n", av[1]);
else
printf("%s does not exist\n", av[1]);
return 0;
}
Usually when you want to check if a file exists, it's because you want to create that file if it doesn't. Graeme Perrow's answer is good if you don't want to create that file, but it's vulnerable to a race condition if you do: another process could create the file in between you checking if it exists, and you actually opening it to write to it. (Don't laugh... this could have bad security implications if the file created was a symlink!)
If you want to check for existence and create the file if it doesn't exist, atomically so that there are no race conditions, then use this:
#include <fcntl.h>
#include <errno.h>
fd = open(pathname, O_CREAT | O_WRONLY | O_EXCL, S_IRUSR | S_IWUSR);
if (fd < 0) {
/* failure */
if (errno == EEXIST) {
/* the file already existed */
...
}
} else {
/* now you can use the file */
}
Yes. Use stat(). See the man page forstat(2).
stat() will fail if the file doesn't exist, otherwise most likely succeed. If it does exist, but you have no read access to the directory where it exists, it will also fail, but in that case any method will fail (how can you inspect the content of a directory you may not see according to access rights? Simply, you can't).
Oh, as someone else mentioned, you can also use access(). However I prefer stat(), as if the file exists it will immediately get me lots of useful information (when was it last updated, how big is it, owner and/or group that owns the file, access permissions, and so on).
FILE *file;
if((file = fopen("sample.txt","r"))!=NULL)
{
// file exists
fclose(file);
}
else
{
//File not found, no memory leak since 'file' == NULL
//fclose(file) would cause an error
}
You can use realpath() function.
resolved_file = realpath(file_path, NULL);
if (!resolved_keyfile) {
/*File dosn't exists*/
perror(keyfile);
return -1;
}
I think that access() function, which is found in unistd.h is a good choice for Linux (you can use stat too).
You can Use it like this:
#include <stdio.h>
#include <stdlib.h>
#include<unistd.h>
void fileCheck(const char *fileName);
int main (void) {
char *fileName = "/etc/sudoers";
fileCheck(fileName);
return 0;
}
void fileCheck(const char *fileName){
if(!access(fileName, F_OK )){
printf("The File %s\t was Found\n",fileName);
}else{
printf("The File %s\t not Found\n",fileName);
}
if(!access(fileName, R_OK )){
printf("The File %s\t can be read\n",fileName);
}else{
printf("The File %s\t cannot be read\n",fileName);
}
if(!access( fileName, W_OK )){
printf("The File %s\t it can be Edited\n",fileName);
}else{
printf("The File %s\t it cannot be Edited\n",fileName);
}
if(!access( fileName, X_OK )){
printf("The File %s\t is an Executable\n",fileName);
}else{
printf("The File %s\t is not an Executable\n",fileName);
}
}
And you get the following Output:
The File /etc/sudoers was Found
The File /etc/sudoers cannot be read
The File /etc/sudoers it cannot be Edited
The File /etc/sudoers is not an Executable
From the Visual C++ help, I'd tend to go with
/* ACCESS.C: This example uses _access to check the
* file named "ACCESS.C" to see if it exists and if
* writing is allowed.
*/
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
void main( void )
{
/* Check for existence */
if( (_access( "ACCESS.C", 0 )) != -1 )
{
printf( "File ACCESS.C exists\n" );
/* Check for write permission */
if( (_access( "ACCESS.C", 2 )) != -1 )
printf( "File ACCESS.C has write permission\n" );
}
}
Also worth noting mode values of _access(const char *path,int mode):
00: Existence only
02: Write permission
04: Read permission
06: Read and write permission
As your fopen could fail in situations where the file existed but could not be opened as requested.
Edit: Just read Mecki's post. stat() does look like a neater way to go. Ho hum.

Resources