Open txt file present in some other directory in C - c

I want to open a file abc.txt present in "../ab cd/Output" folder.
What I have done so far is:
char temp1[100], temp2[10] = "abc.txt";
strcpy(temp1, "../ab\ cd/Output/");
FILE *fp_minenergy = fopen(strcat(temp1, temp2), "r");
On executing it gives segmentation fault.

The problem should be just the file path itself
fopen("../ab cd/Output/abc.txt", "r");
Your actual path is not valid "../ab\ cd/Output/abc.txt", you don't need to escape here anything.

char dirname[51] = "/the/directory";
char filename[51] = "the_file_name.txt";
char full_name[101] = strcat("/the/directory","/");
char full_name = strcat(full_name,filename);
FILE *fp_minenergy = fopen(full_name, "r");
I am adding an extra strcat for the / because I don't know where the directory name is coming from. Someone may specify it without the trailing /. If they specify the / in the name, it doesn't hurt.
/dir/one is equal to dir//two

Related

Fopen function returns null when given an existing path

When trying to open a file with fopen(path, "2"); i get NULL on an existing path
iv'e tried to enter only the file name and it works but i want the program to write the file in the path...
Yes, i write the path with double backslashes "\\" when it's necesary.
Yes the path without doubt exists.
FILE* log;
char directory_path[PATH_LEN] = { 0 };
char directory_file[PATH_LEN] = { 0 };
//directory_path is the directory, entered by the user
//LOG_NAME is the files name without the path - "log.txt"
//#define PATH_LEN 100
printf("Folder to scan: ");
fgets(directory_path, PATH_LEN, stdin);
directory_path[strlen(directory_path) - 1] = 0;
//this section connects the path with the file name.
strcpy(directory_file, directory_path);
strcat(directory_file, "\\");
strcat(directory_file, LOG_NAME);
if ((log = fopen(directory_file, "w")) == NULL)
{
printf("Error");
}
My program worked until i tried to write into a file in order to create a log file. This means that the path is correct without doubt.
Can anyone tell me the problem here?
You have several issues in your code:
For one, fopen(path, "2"); is not valid.
The mode argument needs to include one of a, r, and w and can optionally include b or +.
As another thing, directory_path[strlen(directory_path) - 1] = 0; may truncate the end of your path (if it's over PATH_LEN characters long).
There also may be a possible issue with buffer overflow due to the fact that you copy a string to a buffer of the same size and then concatenate two other strings to it. Therefore, you should change this line:
char directory_file[PATH_LEN] = { 0 };
to this:
char directory_file[PATH_LEN+sizeof(LOG_NAME)+1] = { 0 };
To debug this issue, you should print the string entered and ask for confirmation before using it (wrap this in #ifdef DEBUG).

creating a text file name varying everytime it runs in C

I wanted to know whether there is a piece of code that can help me with making a new file with a different name every time the function with that code runs, for instance I want to write this
FILE * new_file = fopen("D:\C\data\1.txt", "w +" );
as
FILE * new_file = fopen("D:\C\data\%d.txt", next_number, "w +" );
that next_number comes from another procedure which always will get the number following a number stored in a different file.
You can use snprintf().
Example:
char file_name[100]; // assuming path length is at most 100
snprintf(file_name, sizeof(file_name), "D:\\C\\data\\%d.txt", next_number);
FILE * new_file = fopen(file_name, "w+" );

How to set path environment variable in linux in C language code

I want to set a path environment variable in bash by C program.
So I coded using 'setenv' function, But it was not the answer to solve.
Could anybody suggest another way to solve this problem in C programming?
I thought the other solution that the program read the profile file, then modify and save, but actually when I opened this file there's no string I wanted about PATH variable.
You can use setenv() and putenv() to set environment variables. But these will only be set for the given program. You cannot set environment variables for the shell or its parent process.
Here an example to define the Python path.
It is created a string path and append it to the python path.
char *append_path = malloc(sizeof(char) * 1000);
append_path = "/trunk/software/hmac_sha256/:.";
printf("Append to path is:\n%s\n", append_path);
setenv("PYTHONPATH",append_path,1);//Set PYTHONPATH TO working directory https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.1.0/com.ibm.zos.v2r1.bpxbd00/setenv.htm
char *path = Py_GetPath();
printf("Python search path is:\n%s\n", path);
This should append the string to the PYTHONPATH environment variable. For me it is working as stated before.
In case the variable is replaced and not appended, then you just need to read the environment variable before, append the new string and then do the "setenv".
for example
//include string functions
#include <string.h>
....
char *current_path = malloc(sizeof(char) * 1000);
current_path = Py_GetPath();
printf("Current search path is:\n%s\n", current_path);
char *new_path = malloc(sizeof(char) * 1000);
new_path = "/trunk/software/hmac_sha256/:.";
printf("New to add path is:\n%s\n", new_path);
snprintf(current_path, sizeof(char) * 1000, "%s%s", current_path,new_path);//this concatenate both strings
setenv("PYTHONPATH",current_path,1);//Set PYTHONPATH TO working directory https://www.ibm.com/support/knowledgecenter/en/SSLTBW_2.1.0/com.ibm.zos.v2r1.bpxbd00/setenv.htm
char *path = Py_GetPath();
printf("Python search path is:\n%s\n", path);

Regarding FOPEN in C

I am having a problem regarding FOPEN in C.
I have this code which reads a particular file from a directory
FILE *ifp ;
char directoryname[50];
char result[100];
char *rpath = "/home/kamal/samples/pipe26/divpipe0.f00001";
char *mode = "r";
ifp = fopen("director.in",mode); %director file contains path of directory
while (fscanf(ifp, "%s", directoname) != EOF)
{
strcpy(result,directoname); /* Path of diretory /home/kamal/samples/pipe26 */
strcat(result,"/"); /* front slash for path */
strcat(result,name); /* name of the file divpipe0.f00001*/
}
Till this point my code works perfectly creating a string which looks " /home/kamal/samples/pipe26/divpipe0.f00001 ".
The problem arises when I try to use the 'result' to open a file, It gives me error. Instead if I use 'rpath' it works fine even though both strings contain same information.
if (!(fp=fopen(rpath,"rb"))) /* This one works fine */
{
printf(fopen failure2!\n");
return;
}
if (!(fp=fopen(result,"rb"))) /* This does not work */
{
printf(fopen failure2!\n");
return;
}
Could some one please tell why I am getting this error ?
I think you mean char result[100];; i.e. without the asterisk. (Ditto for directoryname.)
You're currently stack-allocating an array of 100 pointers. This will not end well.
Note that rpath and mode point to read-only memory. Really you should use const char* for those two literals.
The error is the array 'char* result[100]', here you are allocating an array of 100 pointers to strings, not 100 bytes / characters, which was your intent.

C - Saving to file crashes

FILE *dataScore;
dataScore = fopen(fileName.dat, "w");
fprintf(dataScore,"%s:%d\n",currentUser,score);
fclose(dataScore);
The file crashes on the line printing to file. I believe it is due to the username but I may be wrong. Thanks in advance. Set the currentUser as 02heasam and score as 20.
looks crazy...
try this way:
int score=20;
int main(void){
char* currentUser = "02heasam";
FILE *dataScore;
dataScore = fopen("fileName.dat", "w");
fprintf(dataScore,"%s:%d\n",currentUser,score);
fclose(dataScore);
}
some explanations:
to fill a char array with a string you would need strcpy or so. Not needed here!
the order might be important (declaration before usage)
a strimng literal "xxx" will automatically terminated by a trailing 0-Byte - NEVER miss to have this in mind!

Resources