Easy C Question

Status
Not open for further replies.

David Ireland

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

All I know is 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. So to clarify...if i were to write C:\directory\text.txt it fails...i tried putting C:\\directory\\text.txt but that fails too.

Thanks.
 
You could try passing in the filename and path as a parameter, that might work... but I'm not 100% sure.

But this type of problem is notorious, I've had VERY similar problems to you in that regard. You think it should work, and it won't.

Hope I've helped, try Googling it if I've not been of much use.
 
I'm not 100% sure, but the problem sounds to me like Windows XP not granting your program access to the directory you are requesting. Just a hunch, but I've seen the same thing on some XP systems. Try using the Windows API calls in console mode to write the file and see what you get. That is my current best guess. I'd have tried it myself before I opened my mouth, but my machine here is currently running Linux and I'm not going to reconfigure it until this project gets done next month. I hope this helps.
 
Code:
#include <iostream>
#include <fstream>
#include <string>

using namespace std;


int main (int argc, char * argv[]) {

string line;
ifstream file (argv[1]);

  if (file.is_open())
  {
    while (! file.eof() )
    {
      getline (file,line);
      cout << line << endl;
    }
    file.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

This is good when you execute your program from a terminal, just put the /path/to/file after you open it for example:
c:\open.exe c:\asdf\another_folder\bleh.txt

if you want to be able to pick your directory in the program you'd have to do this

Code:
#include <iostream>
#include <fstream>
#include <string>

using namespace std;


int main () {

string asdf, line;
cin >> asdf;
ifstream file (asdf.c_str());

  if (file.is_open())
  {
    while (! file.eof() )
    {
      getline (file,line);
      cout << line << endl;
    }
    file.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

Remember c/c++ is case sensative. so if you were to type in c:\ it wouldn't work. It's C:\
 
first... don't drag up old threads.

someone reported this because you dragged it up from the past,

second, that code is c++, not C, so it doesn't even answer the question properly.
 
nuculear youve been warned enough times. temp ban for a week, ive warned you on several occasions about dragging up old threads,

user Nucular temp banned for a week

thread locked
 
Status
Not open for further replies.
Back
Top Bottom