Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open file with fopen, given absolute path on Windows

I'm trying to make a program that counts the number of lines of a file, when I try to pass the absolute path to the fopen function, is simply tells me that is not found, here is my code:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

int main(int argc, char *argv[])
{
    int i=0;
    char array[100];

        char caracteres[100];
        FILE *archivo;
        archivo = fopen("C:\Documents and Settings\juegos psps.txt","r");
        if (archivo == NULL){cout<<"Dont Work";}
        while (feof(archivo) == 0)
        {
                fgets(caracteres,100,archivo);
                i++;
                }
                cout << "Number of lines:" << i ;
                return 0;
}

How should I pass the absolute path to my program so you can open the file?

like image 468
franvergara66 Avatar asked Jul 13 '12 07:07

franvergara66


People also ask

How do I use absolute path in Windows?

To find the full absolute path of the current directory, use the pwd command. Once you've determined the path to the current directory, the absolute path to the file is the path plus the name of the file. For example, if in the cgi-bin directory we had a file called "example.

Does fopen require full path?

fopen() can definitely open files using full path spec. Possibly a typo? Is this on Windows?


2 Answers

It is not working because the compiler examines a backslash in a literal string together with the next character and usually interprets them as one character in all. Such two-char sequences in string literals are called escape sequences.

The sequences \D and \j do not map to anything (contrast this with \n which maps to the newline character), and in this case the standard says that the compiler can interpret them as it chooses. Some compilers choose to ignore the backslash, which in your case would result in the equivalent:

archivo = fopen("C:Documents and Settingsjuegos psps.txt","r");

(You can try creating a file with this name to test if this is what your compiler does).

The correct escape sequence for a backslash is a double backslash, so you should write it as

archivo = fopen("C:\\Documents and Settings\\juegos psps.txt","r");
like image 189
Jon Avatar answered Sep 23 '22 15:09

Jon


Use double slashes:

"C:\\Documents and Settings\\juegos psps.txt"
like image 27
SingerOfTheFall Avatar answered Sep 23 '22 15:09

SingerOfTheFall