C fopen filename parameter as a dynamic variable - c

I want to have the function fopen's filename parameter as a dynamic variable that takes in a ftp client input for my ftp server. I have tried numerous different ways both on this forum and on google but "filename" will still not be recognized by fopen.
else if (strncmp(client->input, "retr", 4) == 0) {
char fname[1024];
// COMMAND LINE: retr filePATHNAME thats why +5
strcpy(fname, client->input+5);
if(fopen(fname, "r") != NULL) {
...
If I put fopen("/pub/test.txt" , "r"), it works so it has to do with something with spaces or quotations or type.
But if i try to do it on the client command line with retr /pub/test.txt or even retr "/pub/test.txt" fopen does not work and will not open the file.
Been stuck on this for the longest time, any help is appreciated.
Thanks

I found the answer.
Thanks to #user3386109 for the hint.
I basically had to clear all the spaces, new lines for the input
strtok(client->input+5,"\r\n\t");

Related

How to discover which files exist in a folder

I have written a program, where it takes an input file, does some operations on it and gives its corresponding output file. i.e., for inp1.txt output is out1.txt, for inp2.txt output is out2.txt and so on, both in different folders.
Right now I have used a file_count variable and have used switch case method, to open the particular file.
The problem is, if I add one more file to the folder, then I have to re-edit the program with another case statement.
Please suggest me the usage of directory pointer in , I browsed all over the net but didnt get an exact solution.
Thanks a lot in anticipation.
There's no way to read the contents of a directory using only standard C APIs, so you'll have to use platform-specific APIs instead:
On *nix systems, you use opendir(3)/readdir(3)/closedir(3) to read the contents of a directory.
On Windows systems, you use FindFirstFile/FindNextFile/FindClose
If you know the file names in advance ie. they follow a pattern like this: f1.txt f2.txt fn.txt then you can loop over the files:
for (int i = 0 -> num_files)
char * filename;
filename = create_your_filename(i)
open(filename)
dostuff
close(filename)
you can follow the same pattern or even edit the filename for the output files.
Otherwise you can also call the program with all the input files in the command:
your_program *.txt
Then all of the file names will appear in argv[], which you can iterate over.
you have to find the files in input folder in runtime before processing. you can sort the files by extension,file name,created date etc...
Here is a simple function that show you if a file (in parameters) is in the path you put in argument.
Return 0 if file exit, 1 if not.
int is_file_enabled(char *path, char *filename)
{
char exec[255], line[255];
sprintf(exec, "ls %s | grep \"%s\"", path, filename);
FILE* cmd_res = popen(exec, "r");
if (cmd_res != NULL)
while (fgets(line, sizeof(line), cmd_res) != NULL)
if (line != NULL) { pclose(cmd_res); return 0; }
pclose(cmd_res);
return 1;
}

Wrong File String for fopen?

I have a text filed called fun on my desktop, but when I pass:
FILE* fp;
if((fp = fopen("/Users/<username>/Desktop/fun", "r")) == NULL)
{
printf("File didn't open\n");
exit(1);
}
fp is null. I have also tried
/home/<username>/Desktop/fun
and many variations, and I still can't seem to get the right file path.I am new to using files and C. Any help would be appreciated.
fopen() can't expand shell keywords.
Change
FILE* fp = fopen("~/Desktop/fun.txt", "r")
to
FILE* fp = fopen("/home/<yourusername>/Desktop/fun.txt", "r")
Characters like '~', '*' are interpreted by the shell and expanded.
You can't use ~ in pathnames to represent the user's home directory. That notation is recognized by shells and some other applications, but it's not part of the Unix filesystem interface. You need to spell out the user's actual home directory.
fopen("/home/username/Desktop/fun.txt", "r")
The ~ in the path is probably the issue. It's your shell that expands that on the command line. fopen doesn't invoke a shell to do substitutions on the path, you'll need to do that yourself.
So pass a complete (relative or absolute) path to fopen, not something that requires shell expansions (~, globbing patterns or shell variables).
You need to expand ~. Use getenv("HOME").
getenv at opengroup even provides some code:
const char *name = "HOME";
char *value;
value = getenv(name);
/*===exphome===([o]i)==================================================
* if SIn is not NULL then
* if SIn starts with '~'
* then expands $HOME, prepends it to the rest of SIn, and
* stores result in SOut or, if SOut==NULL, in a new
* allocated string and returns it
* else if SOut!=NULL
* then copies SIn into SOut and returns SOut
* else returns duplicated SIn
* else returns NULL
=*===================================================================*/
char *exphome(char *SOut, char *SIn)
{char *Rt= NULL;
char *envhome= NULL;
if(SIn)
if(*SIn=='~' && (envhome=getenv("HOME")))
{Rt= malloc(strlen(SIn)+strlen(envhome)+1);
strcpy(Rt, envhome); strcat(Rt, SIn+1);
if(SOut) {strcpy(SOut, Rt); free(Rt); Rt= SOut;}
}
else if(SOut) {strcpy(SOut, SIn); Rt= SOut;}
else Rt= strdup(SIn);
return Rt;
} /*exphome*/
and then
fopen(exphome(NULL, yourfile), ...)
It looks like the answers have prompted edits of original problem. However, as it is currently written there is NO extension on the file name? Is this really true? or does the file end in "*.txt" etc.?
Double-check that you have the correct full file path. Go to the file, right-click on it and select "properties". Are you entering in the path exactly as it is shown, including any suffixes? I.e. if the file is called "file.txt", make sure you include the ".txt" suffix in your code.

I am unable to open a file in c

i created a text file in d: drive named abc. I am unable to open it. Please tell me how to do so.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
clrscr();
fp = fopen("D:/abc.txt","r");
if(fp == NULL)
{
printf("\nCannot open");
getch();
exit(1);
}
fclose(fp);
getch();
}
You have a typo, try
fp = fopen("D:\\abc.txt","r");
instead.
Or if the file is in the same folder as the program:
fp = fopen("abc.txt","r");
correct the path, it should be "D:\\abc.txt"
You file-path looks a little bit strange. Change it to
fp = fopen("D:\\abc.txt","r");
This might work.
Apart from that, include <errno.h> and check for it, if it has failed.
fp = fopen("D:/abc.txt","r");
should be
fp = fopen("D:\\abc.txt","r");
in use \ in path instead of / in Windows and extra \ for escape sequence.
EDIT:
As you commented to others answers that fp = fopen("D:\\abc.txt","r"); also not working then check what is name actually. You might given probably wrong name by mistake, check whether you have error like this.
(1) open command prompt
(2) use DIR command to print name of file:
c:\Users\name> D:
D:\> DIR
Volume in drive D is FUN BOX
Volume Serial Number is B48A-3CE7
Directory of d:\
27-02-2013 19:23 0 abc.txt.txt
26-02-2013 22:05 <DIR> BOLLYWOOD MOVIES
27-02-2013 19:31 0 x
2 File(s) 0 bytes
1 Dir(s) 11,138,654,208 bytes free
file name is abc.txt.txt but when you see this in folder extension doesn't appears and file name looks abc.txt
I am Linux user and I normally do this mistake in Windows. That's why. May be it help you!
If you are working with TurboC put that file in the BIN directory of TC.
And specify the path as fp = fopen("abc.txt","r"); instead of any other alternate path.
The Next time , try to make the error more specific by using perror() function.
Perror() will interpret the error code , this will help you to waste less time , trying to find the type of error.
add this in your code...
if(fp == NULL)
{
perror(fp);
}
On running i got the perror message
No such file or directory.
(since i ran the program , and tried to read a file , without creating it first)
See , if this was the same problem , in your case

Reading from files passed as command line arguements

I am trying to parse a given textfile, but so far, my program does not seem to be reading properly.
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE *fr; //file pointer
int buildingFloors = 1;
printf("sanity check\n");
fr = fopen (argv[0], "r");
fscanf(fr, "%d", &buildingFloors );
printf("%d\n", buildingFloors);
fclose(fr);
return 0;
}
I compile the program and run it on my redhat linux machine with the following command:
./sjf file.text
file.text is a text document with a "4" as the first character. So I would expect my output to be
sanity check
4
However, when I run my program I instead get
sanity check
1
Which implies that fscanf didn't properly read in the first character -- 4. Do I have some syntax error that's preventing the expected code functionality? Am I supposed to scanf for a character, and then convert that to an int somehow?
argv[0] is the name of the program (./sjf in your case), so you're trying to read in your own program's executable. Use argv[1] instead to get the first real program argument.
One thing which immediatly comes to mind is that the program args include the executable name as the first element
argv[0] is "sjf"
argv[1] is "file.text"
so you should be using
fr = fopen (argv[1], "r");
Remember when debugging to always try and narrow the problem down, if you know the location of the error the cause often becomes obvious or at least investigatable.
In this case you should check argc >= 2, print out argv[1] to ensure you are trying to open the right file, then also check that the file was opened successfully.
Finally check the fscanf error codes to see that fscanf was able to read the number.
Your code looks clear and straight-forward, but there is one important thing missing: error handling.
What happens if the file you want to open does not exist? fopen returns NULL in that case.
What happens if the file does not start with a number? fscanf returns the number of fields that have been successfully read, so you should check that the return value is at least 1.
You need to somehow handle these cases, probably by printing some error message and exiting the program. When you do that, be sure to include the relevant information in the error messages. Then you will find the bug that the other answers have already mentioned.

Text File Parsing in C - Calling a Batch File Or Not

This website is a tremendous source of knowledge, it has helped me countless times in the past.
I just started learning C on my own - up until now I just wrote a few batch files.
So I humbly ask for your help - I'd like some guidelines on how to write a C program that would:
1) Open a text file that contains the following
"batch1.cmd" "argument1" "1"
"batch2.cmd" "argument2" "0"
"batch3.cmd" "argument3" "1"
2) Parse it to find "0" or "1"
If "1" call he specified batch file with its argument
If "0" go next line - I will be updating the text file on a regular basis, so I would just have to change 1 or 0 and not rewrite all of those lines.
I have found a lot of help regarding parsing in C on the internet already, but no tutorial regarding how to achieve that.
I am aware that this might seem very easy and that I must appear as someone very lazy but I assure you I've been at it for three days now, without any success.
I am not necessarily asking for a complete script, just an answer like "look into the following function, its correct syntax is yadda yadda" and so forth.
I think I would have to use
int Search_in_File(char *fname, char *str)
{ FILE *fp;
fp=fopen("c:\\batchlist.txt", "r");
and
system("c:\\batch1.cmd argument1");
but I somehow cannot "connect the dots."
Thanks in advance!
Have a look at http://en.wikipedia.org/wiki/C_file_input/output - you're very close. Once you've opened the file, you need to read the lines or characters from the file, and based on what you find, execute the system command.
That wiki page will show you how - it has some handy example code too :)
int Search_in_File(char *fname, char *str)
{ FILE *fp;
char line[100],a[100],b[100],c[100];
fp=fopen("c:\\batchlist.txt", "r");
if( !fp ) ... errorhandling here ...
while( fgets(line,100,fp) )
{
if( strchr(line,'\n') ) *strchr(line,'\n')=0;
if( 3==sscanf(line,"%s%s%s",a,b,c) && !strcmp(c,"1") ) /* "%s" breaks at whitespaces, attention for whitespaces in your strings here! */
{
sprintf(line,"%s %s",a,b);
system(line);
}
}
...
fclose and so on ...
}

Resources