Open file with fopen function

Hi, i really want to know how i can open file using fopen function while i am not sure where the txt file located. I mean, if i make a simple program and then i want to share it with my friend, how i can tell the program to open the txt file while i don't know where the txt file is located?

--> The exe is located in a some folder and the txt is located in the sub folder
You cant do that.
You will have to specify full or relative path to fopen
Something like "/usr/home/filename.txt or "dir/filename.txt"
You can use e.g. cin/cout to ask the user for the path and file name.
Three simple ways:

1. Have the user specify the filename when starting your program. 
This is how many, many applications work.
Drag and drop the file onto the exe and it'll work.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main( int argc, char** argv )
{
  FILE* f = NULL;

  if (argc != 2)
  {
    printf( "usage: %s FILENAME\n", argv[0] );
    return 1;
  }

  f = fopen( argv[1], "r" );
  if (!f) ...

  ...

  fclose( f );
  return 0;
}

2. Pipe the file into standard input. 
Many Unix utilities work this way.
1
2
3
4
int main()
{
  // use stdin
}
C:\Users\Eric\prog> a.exe < filename.txt
% ./a.out < filename.txt


3. Ask the user for it. 
This method is pure disadvantage; user must know how to enter filename without being able to use tab-completion or any other helps to find it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main()
{
  FILE* f = NULL;

  char filename[ 1024 ] = { 0 };
  printf( "file? " );
  fflush( stdout );
  if (!fgets( filename, 1024, stdin ) || filename[1023])
  {
    fprintf( stderr, "bad filename!\n" );
    return 1;
  }

  f = fopen( filename, "r" );
  if (!f) ...

  ...

  fclose( f );
  return 0;
}

Hope this helps.
Hi guys, thanks for the solutions. But i had solve this.
I just need write the directory path like this
"FILE* file;"
"file=fopen(".\\subfolder\\text.txt","r");"

Before, i tested to write like this "file=fopen("text.txt","r");" and its work
i don't know for sure, but i think it tells the program to find this file in same directory as the exe file located

so i just googling around and found out about how to access the subdirectory. it just need a dot before the backslash

Thanks guy
Last edited on
Anything that starts with a slash is an absolute path.
Anything that doesn't is a relative path.

\foo\bar is an absolute path.
foo\bar is a relative path.

(Note that the drive letter is a distinct issue on windows:
C:\foo\bar is absolute;
C:foo\bar is relative.)

Consequently, your program would work fine with just

 
FILE* file = fopen( "subfolder\\text.txt", "r" );  // relative path 

Hope this helps.
Thanks Duoas, that is really helpfull.
Last edited on
Topic archived. No new replies allowed.