fopen ordering in C affecting it strangely [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have this code:
FILE *setup=fopen(strcat(cwd,"setup.txt"),"r");//navigates up to setup file
...//(doing stuff with setup)
fclose(setup);
FILE *paths=fopen(strcat(cwd,"stuff.txt"),"r");
char buff2[1024];
fgets(buff2,200,paths);
char thing[1024];
strcpy(thing,buff2);
printf(thing);
fclose(paths);
but it executes differently based on if I do code with setup or the code with paths first - only the first one works properly, the second just creates gibberish whenever fgets is called. fclose returns 0 as it should. The specific way I look at the second file doesn't seem to affect it. What's happening here?

Don't strcat()!
FILE *setup=fopen(strcat(cwd,"setup.txt"),"r");//navigates up to setup file
// cwd now has "...setup.txt"
FILE *paths=fopen(strcat(cwd,"stuff.txt"),"r");
// cwd now has "...setup.txtstuff.txt"

strcat() modifies cwd.
So if cwd originally contains "/home/username/", the first call changes it to "/home/username/setup.txt".
The second call appends to that, so it tries to open "/home/username/setup.txtstuff.txt". This filename almost certainly doesn't exist, but you aren't checking for an error.
And if that filename is longer than the space allocated to cwd, you'll get a buffer overflow and undefined behavior.
Use a different variable to hold the filename to open.
char filename[MAXLENGTH];
sprintf(filename, "%s%s", cwd, "setup.txt");
FILE *setup = fopen(filename, "r");
...
fclose(setup);
sprintf(filename, "%s%s", cwd, "stuff.txt");
FILE *paths = fopen(filename, "r");
...
fclose(paths);

Related

Why doesn't fprintf(outputFile,"") work from inside gdb? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
When I try to debug a piece of code from inside gdb and the control reaches a fprintf statement to an outputFile it doesn't show the output lively in the file and it just shows empty, despite working fine with just a simple run of the program from the terminal.
How do I get my output lively on the outputFile when debugging from inside gdb?
NOTE: I am not talking about gdb precisely I am just asking how to get the output lively in the file on the fly while debugging from gdb.
How do I get my output lively on the outputFile when debugging from inside gdb?
Do this:
(gdb) call fflush(0)
This will cause the program being debugged to flush all of its output streams.
This is probably due to stream buffering:
Characters that are written to a stream are normally accumulated and transmitted asynchronously to the file in a block, instead of appearing as soon as they are output by the application program. Similarly, streams often retrieve input from the host environment in blocks rather than on a character-by-character basis. This is called buffering.
Try out this example:
#include <stdio.h>
int main(void) {
FILE *f = fopen("foo.txt", "w");
printf("Break here and go line by line.");
fprintf(f, "Bar\n");
printf("Nothing in foo.txt yet.");
fflush(f);
printf("Buffer has been written to foo.txt now.");
fprintf(f, "Baz\n");
printf("Baz is still only in the buffer.");
fclose(f);
printf("The buffer was written to the file before closing.");
}

Getting a core segmentation fault when trying to read a file from argv[] [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I have been getting a core segmentation fault when trying to read a file from argv[]. I have created the file and I am very sure that I am trying to access the correct memory address. However, when trying to open the file I receive the core dump.
Here is the relavent code-
for (int x=1;x<argc;x++){
int buffsize=2056;
char buff[buffsize];
FILE* thefile;
thefile=fopen("argv[x]","r");
if (thefile == NULL) {
fprintf(stderr, "%s cannot open file '%s'\n", argv[0], argv[1]);
return 2;
}
The command line argument I am passing in is
./words testfile.txt
with ./words being the compiled code.
I actually found the solution, it seems to be the quotes in argv in the fopen, why is this?
Oops! I believe the line
thefile=fopen("argv[x]","r");
Should be:
thefile=fopen(argv[x],"r");
This is because "argv[x]" is not code, it's a string. What's that? Is that a path to a file? It's not compiled as code. It doesn't refer to one of the arguments in argv.
You might also want your log message to use that filename. Notice the argv[x]:
fprintf(stderr, "%s cannot open file '%s'\n", argv[0], argv[x]);

How do I create a file in the same directory as the executable when run by root? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Improve this question
I have a program written in C that creates and reads a config file. It assumes that the config file is in the same directory as it is.
The program is run by fcron as root. If root runs this program, then the config file is created in root's home directory. It needs to be created in the user's directory where the program is.
I don't know enough about user management in linux to solve this, so the only way I can think to solve this is to get the executable's path by modifying argv[0].
Is there a better way?
Does the program have to run as root? Using the crontab for the user would ensure the right home directory, file permissions, etc. as well as security advantages.
You could modify the job to run in a desired working directory. I believe the syntax would be something like:
15 7 * * * cd /home/myuser/ && /usr/bin/myprogram
Or pass it as an argument, (see various programs for examples of things like --config-path=~/mycustomconfig). These have more flexibility, say if the program is installed once for multiple users.
Alternatively, to get the main executable path in the process, you can read /proc/self/exe, you might then use dirname to get the directory from the full path. e.g.
char path[MAX_PATH];
ssize_t len = readlink("/proc/self/exe", path, MAX_PATH);
if (len > 0 && len < MAX_PATH) {
path[len] = '\0';
char *directory = dirname(path);
}
In either case, the regular file I/O functions will create a file owned and writable by root, if this is not desired, chown(path, owner, group) might be used. stat(path, buf) on the home directory could be a way to get the ID for chown but not something I ever considered and there may be cases the directory is owned by the "wrong" user.

file opening and writing in c [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
FILE *fp1;
if((fp1 = fopen("abc.txt", "w")) != NULL)
{
fprintf(something);
fclose(fp1);
}
I am trying to compile this file and all related file using developer command prompt and trying to run it from there. But while running it says this filename.exe has stopped working. It is not able to create the file abc.txt .
You almost certainly don't have write permission in the directory you are attempting to create abc.txt in. The code would be better if you handled the error case:
if ((fp1 = fopen("abc.txt", "w")) == NULL) {
perror("abc.txt");
exit(1);
}
My guess is your output will be "abc.txt: Permission denied"
You also have a problem that your fprintf() ought to be fprintf(fp1, something) (where something is presumably your format string and some variables).

C open file using a function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am pretty new to C and I am struggling to write to files form my C program. In this program I open files to read from as well as files to write to, so I thought I'll make a function that opens the file for me. This is what I did
FILE *open_file(char* filename, char* mode)
{
FILE *f;
f = fopen(filename, mode);
if(!f)
{
perror(filename)
exit(EXIT_FAILLURE);
}
return f;
}
And this is how I call the function:
FILE *infile = open_file(args.infile_name, "r");
FILE *rm_file = open_file(args.rm_file, "r");
FILE *ex_file = open_file(args.ex_file, "w");
Those function calls are spread throughout the program. first I had the mode "r" hardcoded in there because I only needed to read from files, but now I also want to write for a file, so I made a parameter for the modus in which the file should be opened. It worked fine before, but now it does nothing. I compiles fine, without any errors, warnings and/or notes. Also valgrind tells me that everything is fine. Any thoughts on this? Thanks in advance.
EDIT: I forgot to add the line where I returned f, I added it now. It was in my code already (ofcourse, you can't let a non void function return nothing).
EDIT: Better explanation of the "error": I am trying to read words from a file and store them in a tree like datastructure. This is working fine, I can look them up and all so no problems here. After adding words to the tree I print the amount of words found in the file and the amount of words added to the tree (I don't add words that are already there). Now I want to export the tree to a file so I need to open a file I can write to. Since I had hardcoded the open_file with the read-only modus, I added a parameter for the modus. But when I run the program now it gives no error (so the filepointer isn't NULL) but just says 0 words found in file and 0 words added. Also the file I print to stays empty. Hope this makes it a little clearer
FILE *open_file(char* filename, char* mode)
{
FILE *f;
f = fopen(filename, mode);
if(!f)
{
perror(filename)
exit(EXIT_FAILLURE);
}
}
Your function doesn't return anything. Simply add return f; at the end. Seems your wrapper is doing little work though, could have also put this code where you are using it directly, instead of having this function.

Resources