Re: fopen
Re: fopen
- Subject: Re: fopen
- From: Mark Wagner <email@hidden>
- Date: Mon, 02 Jul 2012 13:14:29 -0700
On Mon, Jul 2, 2012 at 10:11 AM, rckrueger <email@hidden> wrote:
> I am just learning c, and this is a beginner's question. I am using Xcode 4
> (Command Line tool) to create a program that will read a simple text file (a
> number 1234). When I use the code:
>
>
> #include <stdio.h>
>
> int main(int argc, const char * argv[])
> { FILE *inputfile; // a pointer to the input file
> inputfile = fopen("test.txt", "r");
This tells the program to open the file "test.txt" in the current
working directory. Unless you're running this program from the
command line, the location of the current working directory is
unpredictable.
>
> to find and open the test.txt file which I have in the Project folder, same
> level as the main.c file, I get the error message:
>
> Thread 1: EXC_BAD_ACCESS (code=1, address=0x68
>
> which I guess means that it can't find the file.
Not quite. It means that the program failed to open the file, but it
then went on to use the file as if it had been successfully opened.
You need to check to see if fopen() succeeded or not. Since fopen()
returns NULL when it fails, error-checking would look something like
this:
inputfile = fopen("test.txt", "r");
if(NULL == inputfile)
{
/* Put your error-handling code here. It could be something as
simple as "return 0;", or you could start learning about the standard
library's error-reporting functions. */
}
>
> When I use this line to look for the file on the desktop:
>
> inputfile = fopen("/users/robertkruegertiger/desktop/test.txt", "r");
> the program works as expected.
This works because you're giving the program an absolute path, rather
than the relative path used in the first version.
> How do I get the program to find the test.txt file in the Project folder.
You could provide the absolute path to the file, or you could run the
program from the command-line, or you could set the current working
directory from within the program. There's probably also a way in
Xcode to set the current working directory, but I don't know what it
is.
--
Mark Wagner
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden
References: | |
| >fopen (From: rckrueger <email@hidden>) |