# Simple C Question

This is a discussion on Simple C Question within the C Programming forums, part of the General Programming Boards category; How can i open a file for reading and writing in a directory other than "C:\"?? This is the only ...

1. ## Simple C Question

How can i open a file for reading and writing in a directory other than "C:\"??

This is the only way I know how to do this...

Code:
if((fp = fopen("C:\hello.txt, "w")) != NULL)
{

fprintf(fp, "Hello.");
fclose(fp);

}

else
puts("Write Failed.");
So when I do that all i can read and write are files in C:\ and no other directory...like C:\whatever...if i try that it fails. To clarify, If i were to write C:\directory\text.txt in up there, it fails. I also tried C:\\directory\\text.txt but that fails too.

Thanks.

2. [code]
Code:
if((fp = fopen("C:\hello.txt, "w")) != NULL)
You only have the 1 " which would be causing problems. Use 2 and put whatever directory you want to write/read a file in, inside them like.

[code]
Code:
if((fp = fopen("D:\blah\hi.txt", "w")) != NULL)

3. "c:\\directory\\test.txt" should work, as should "c:/directory/test.txt". If it fails, look at the error reason. You can use the perror() function to do this.

Edit:

Originally Posted by John_
Code:
if((fp = fopen("C:\hello.txt, "w")) != NULL)
You only have the 1 " which would be causing problems. Use 2 and put whatever directory you want to write/read a file in, inside them like.

Code:
if((fp = fopen("D:\blah\hi.txt", "w")) != NULL)
You must use two backslashes otherwise they'll be treated as special characters: "D:\\blah\\hi.txt". For that reason, "d:/blah/hi.txt" is a lot more readable and generally preferred.

4. ## Oops

Haha yah sorry...thats not actually in my program that was a typo..i have that and it still doesnt work...this is exactly what is in my program...

Code:
int main (void)
{
FILE *fp;

if((fp = fopen("C:\folder\text.txt", "w")) != NULL)
{

fprintf(fp, "Hello.");
fclose(fp);

}

else
puts("fail");

return 0;
}
So when that is run...i get the FAIL message.

5. Originally Posted by almo89
Code:
if((fp = fopen("C:\folder\text.txt", "w")) != NULL)
A point to consider: what are \f and \t? [Form feed and tab?]

Use forward slashes.

6. Oh yea I forgot the extra \ for an esacape character in my example. And I also messed up the code tags hehe. I'll leave my original reply as is for consistency, you guys have given the correct answer anyway.