working with files on "start without debugging" - c

I'm programming in C, and
I have the following problem:
I use fopen and try to read from a csv file, that is currently storred in the folder of the exe file of the program.
the program works fine in debug mode and release mode, but when I try to run the program in "start without debugging" on visual studio 2008 express edition, the program stops working and windows is showing a message: "*.exe has stopped working. a program caused the program to stop working correctly. windows will close the program and notify you if a solution is available".
I've tried running the program on several computers, and it's the same.
another information I can give you is that if I enter the full path of the file (C:....file.csv) - then is works just fine, without any problem.
I know I didn't write any code, but I hope someone will have an idea why this can happend.
thanks is advance.

Your program is not finding the csv file, fopen() fails and return a null pointer, you try to use it without checking and your program crashes (just my guess).
Firstly, you must make a check to see if fopen() could indeed open your file:
FILE* f = fopen("file.csv", "r");
if(f == NULL) {
/* print some meaningful error */
} else {
/* use the file */
}
Secondly, you may solve the problem by executing your program from the same folder the file is present. I am not a Windows guy, but if you create a link to the ".exe", in its properties may have some configuration called "Working Directory" or something like that, that you may set to the path on where the file can be found.
Every process has a working directory, that is usually the directory from where it was started, though it may be inherited from the parent process and it may be changed programmatically. If you do not specify the full path when loading a file, the process will search for the file in its current working directory.

Related

How to use relative path to open files in C using xcode?

I need to make a game in C for my finals. The user should input the map file he wants to play.
Here's my simple code:
int main(){
FILE *map;
char fileToRead[100];
do{
printf("Insert file name: ");
fgets(fileToRead, 100, stdin);
map = fopen("/Users/rajunior/Desktop/map_2.txt", "r");
//map = fopen(fileToRead, "r");
printf("%s", fileToRead);
If I use the "map = fopen("/Users/rajunior...)" hardcoded, it works!
But I need to use the second (commented) option; the first one is useless for my purpose.
In other words, I need the fileToRead to be in the same directory as my .c, but how?
screenshot: https://imgur.com/a/DbX9tw4
Option 1: Install the command line tools. Put the C file and the text file in the same directory. Open a terminal window. Compile and run from the command line. If I recall correctly, the command line tools download can be found in Preferences.../Downloads.
Option 2: Go to the Product/Scheme/Edit Scheme... menu. When the dialog box appears, select Run at the left and Options at the top. Then look for Working Directory. Set the working directory to point to the directory where the text file is.
This was going to be a comment, but it is too long for comfort.
You'll need to know the current directory of the process when it is run. If you run it from the shell, the current directory of your program will be the same as the current directory of the program. If you run it from within XCode, I've no idea what the directory will be, but it probably won't be where the source is — it'll be in a build directory of some sort, probably.
Your program can find out where it is run from with getcwd(). Then you'll be able to tell how to chdir() to the directory where the source is (as long as the program knows where the source is, because you told it somehow — argument or command line variable, or …). Or you can determine how to create a relative path name that will find the file in the source directory.
There's probably an XCode (maybe Objective-C) way to find the information, perhaps via plists.
I don't code for a Mac; I only code on a Mac, and I run XCode itself rather seldom.

Get current path when C app is launched from /bin/ in Linux

So, I am working on an application that reads files, much the way vim or cat would, where you type "appname /path/to/file.txt" and it passes the file path as a perameter to the program which manipulates the file in some way.
I have run into a roadblock though. In vim, cat, or a similar program, you can type "appname file.txt", and it will read the file in the current directory that you launch the application from terminal in.
For example, I want to edit a file my documents directory. I type "cd ~/Documents", and then I can either type "vim ~/Documents/Essay.txt", or I just can type "vim Essay.txt".
My application will be stored in a binary file in the /bin/ directory so I can launch it from anywhere using the Terminal, but how do I pass the path name of the directory I am in when I call it from terminal?
As I am a new Linux developer (I have always worked with the .NET launguages in Windows) I am not sure weather this is handled by the Linux terminal, or by the C application itself.
Any help or suggestions would be much appreciated!
Also, if there is a more efficiant way to run it from the terminal than sticking it in the /bin/, let me know.
If you want to get the directory the process was run from you can use the system call getcwd to copy a string into a buffer and return it. The kernel keeps track of this for every process.
e.g.
char buf[100];
printf("Current directory: %s\n", getcwd(buf, 100));
The working directory can be changed, but will default to where the process launched.
This should work just fine without you having to do anything special. Did you try something that didn't work as you expected?
Generally you don't put user programs in /bin. I would store your program in /usr/local/bin.
https://unix.stackexchange.com/a/8658

AppleScript: "file is already open" but "file wasn't open"

Because of my slightly obsessive personality, I've been losing most of my productive time to a single little problem.
I recently switched from Mac OS X Tiger to Yosemite (yes, it's a fairly large leap). I didn't think AppleScript had changed that much, but I encountered a problem I don't remember having in the old days. I had the following code, but with a valid filepath:
set my_filepath to (* replace with string of POSIX filepath, because typing
colons was too much work *)
set my_file to open for access POSIX file my_filepath with write permission
The rest of the code had an error which I resolved fairly easily, but because the error stopped the script before the close access command, and of course AppleScript left the file reference open. So when I tried to run the script again, I was informed of a syntax error: the file is already open. This was to be expected.
I ran into a problem trying to close the reference: no matter what I did, I received an error message stating that the file wasn't open. I tried close access POSIX file (* filepath string again *), close access file (* whatever that AppleScript filepath format is called *), et cetera. Eventually I solved the problem by restarting my computer, but that's not exactly an elegant solution. If no other solution presents itself, then so be it; however, for intellectual and practical reasons, I am not satisfied with rebooting to close access. Does anyone have insights regarding this issue?
I suspect I've overlooked something glaringly obvious.
Edit: Wait, no, my switch wasn't directly from Tiger; I had an intermediate stage in Snow Leopard, but I didn't do much scripting then. I have no idea if this is relevant.
Agreed that restarting is probably the easiest solution. One other idea though is the unix utility "lsof" to get a list of all open files. It returns a rather large list so you can combine that with "grep" to filter it for you. So next time try this from the Terminal and see if you get a result...
lsof +fg | grep -i 'filename'
If you get a result you will get a process id (PID) and you could potentially kill/quit the process which is holding the file open, and thus close the file. I never tried it for this situation but it might work.
Have you ever had the Trash refuse to empty because it says a file is open? That's when I use this approach and it works most of the time. I actually made an application called What's Keeping Me (found here) to help people with this one problem and it uses this code as the basis for the app. Maybe it will work in this situation too.
Good luck.
When I've had this problem, it's generally sufficient to quit the Script editor and reopen it; a full restart of the machine is likely excessive. If you're running this from the Script Menu rather than Script Editor, you might try turning off the Script Menu (from Script Editor) and turning it back on again. The point is that files are held by processes, and if you quit the process it should release any lingering files pointers.
I've gotten into the habit, when I use open for access, of using try blocks to catch file errors. e.g.:
set filepath to "/some/posix/path"
try
set fp to open for access filepath
on error errstr number errnom
try
close access filepath
set fp to open for access filepath
on error errstr number errnom
display dialog errnum & ": " & errstr
end try
end try
This will try to open the file, try to close it and reopen it if it encounters and error, and report the error if it runs into more problems.
An alternative (and what I usually do) is that you can also comment out the open for access line and just add in a close access my_file to fix it.

permission denied for rename function in C on windows

I have an application developed in C. This application is supported across multiple platforms. There is one functionality where we are transferring files via file transfer protocol to different machine or to any other directory on local machine. I want to include a functionality where I can transfer the file with some temporary name and once the transfer is complete, I want to rename the file with the correct name (the actual file name).
I tried using simple rename() function. It works fine in Unix and Linux machines. But it does not work on Windows. It is giving me an error code of 13(Permission denied error).
First thing, I checked in msdn to know the functionality of rename if I have to grant some permissions to the file etc.
I granted full permissions to the file (lets say it is 777).
I read in few other posts that I should close the file descriptor before renaming the file. I did that too. It still gives the same error.
Few other posts mentioned about the owner of the file and that of the application. The application will run as a SYSTEM user. (But this should not affect the behavior, because I tried the same rename function in my application as follows:
This works fine from my application:
rename("C:/abc/aaa.txt","C:/abc/zzz.txt");
but
rename(My_path,"C:/abc/zzz.txt");
doesn't work, where My_path when printed displays C:/abc/test.txt.
How can I rename a file? I need it to work on multiple platforms.
Are there any other things I should be trying to make it work.?
I had this same problem, but the issue was slightly different. If I did the following sequence of function calls, I got "Permission Denied" when calling the rename function.
fopen
fwrite
rename
fclose
The solution was to close the file first, before doing the rename.
fopen
fwrite
fclose
rename
If
rename("C:/abc/aaa.txt","C:/abc/zzz.txt");
works but
rename(My_path,"C:/abc/zzz.txt");
does not, in the exact same spot in the program (i.e. replacing one line with another and making no changes), then there might be something wrong with the variable My_path. What is the type of this variable? If it is a char array (since this is C), is it terminated appropriately? And is it exactly equal to "C:/abc/aaa.txt"?
(I wish I could post this as a comment/clarification rather than as an answer but my rep isn't good enough :( )

fopen and windows

This is the first time I'm coding C in Windows and a weird bug is driving me crazy.
I'm trying to open a .txt file using fopen, and it keeps giving me the "file doesn't exist" error (it also gave me the "no permission" error, once).
My code is as follows (doesn't get any simpler than that):
FILE *file;
if((file=fopen("C:\\Users\\ste\\Desktop\\file.txt", "r"))==NULL)
{
printf("Cannot open file.\n");
puts(strerror(errno));
getchar();
exit(1);
}
Am I missing something here? Thanks in advance!
I bet you have the Windows "hide extensions" bugfeature turned on. So the file which is really called "file.txt" appears in your Explorer as "file". And if it appeared to be "file.txt" in the Explorer, it would have to be named "file.txt.txt" on the hard drive.
The code itself is fine assuming what it does is what you are wanting.
"r" requires that the file already exists (it wont create one for you) so you need to make sure that the path is correct. Is the desktop path right, not on another drive etc?
The permission error would occur if it was executed by a user other than "ste", or of course if somthing had changed the permissions on that file path some how to prevent access.

Resources