2

In C# when you need to manipulate files you can use the @ symbol to avoid changing the "\" in the files name.

Example:

string fileName = @"C:\Users\username\Documents\text.txt";

But in C I can't use the @ symbol. So I have to replace "\" for "/" or use "\ \":

fopen = ("C:/Users/username/Documents/text.txt","r");

or

fopen = ("C:\\Users\\username\\Documents\\text.txt","r");

Is there some trick in C for avoid all this work?

  • What extra work is involved in using forward slashes? Is this a real problem for you, or are you just wondering? – Caleb Oct 26 '18 at 14:15

2 Answers2

1

For the most part, don't put absolute literal pathnames, especially not ones with Windows-specific notation, in your source files. Load or construct pathnames from some sort of input data so that your program is not locked in to the filesystem layout of the box you developed it on.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
-1

You can write a small helper function to convert all the backspaces to forward spaces.

void fileconvert(char *filename)
{
    while(*filename !='\0')
    {
        if (*filename == '\')
        {
            *filename = '/';
        }
        filename++;
    }
}

You can use it as below.

FILE *fp;
char filename[] = "C:/Users/username/Documents/text.txt";

fileconvert(filename);
fp = fopen(filename,"r");

This is probably how the @ operator works in C#

Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31
  • 1
    This code would not even compile and does nothing like what OP wants. Moreover if OP is okay with using forward slashes, there's no need for any conversion. Windows (and DOS) have **always** supported forward slashes. – R.. GitHub STOP HELPING ICE Oct 26 '18 at 12:43
  • please refer https://stackoverflow.com/questions/11466139/open-file-with-fopen-given-absolute-path-on-windows for forward slash. Regarding compile - the code given is a snippet and not complete code – Rishikesh Raje Oct 26 '18 at 16:09