The title doesn't really do this topic justice. It's actually quite simple, my problem that is. I have a program (code below) written in the C language. I want this program to create an exe file that can be ran through the command prompt console window and that will also take a text file as a parameter. So, long story short; I need it to say this on the command line in CMD:
C:\Users\Username\Desktop\wrapfile.exe content.txt
My only problem is getting the code right. I want to tell Visual Studio: "The file you should open is given in the command prompt window as a parameter, there is no set location..."
How do I do that?
Here is my working code (Although you will have to change a few things in the *fp definition.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *fp; // declaring variable
fp = fopen("c:\\users\\*Put you're PC username here*\\Desktop\\contents.txt", "rb"); // opens the file
if (fp != NULL) // checks the return value from fopen
{
int i;
do
{
i = fgetc(fp); // scans the file
printf("%c",i);
printf(" ");
}
while(i!=-1);
fclose(fp);
}
else
{
printf("Error.\n");
}
}
Thanks everyone!
As Ken said above, the arguments of the main method are the values that you pass in from the command line. Argc is 'argument count' and argv is 'argument values'. So to open the fist argument passed in from the command line, change
fp = fopen("c:\\users\\*Put you're PC username here*\\Desktop\\contents.txt", "rb"); // opens the file
to
fp = fopen(argv[1],"rb");
Just make sure to do error checking (ie argv[1] is not null) before you try to fopen the input. Also FYI, in your case argv[0] will be the name of your executable.
Related
I have an assignment that is requiring that my program takes in a plain text file at execution time and manipulates it to keep track of a vending machine inventory.
The file has to contain 12 rows with the details of each item in the machine that is used to populate data structs.
Would passing the file to the program require command line arguments or is it something different?
I am using a GCC compiler.
I have tried adding the address of the file to the execution command but nothing came of that.
I've assumed you need the file path to be accepted as an input to the program.
If so then it depends on how you would like to pass this information to the program, but I'm not convinced that passing command line arguments could be considered an runtime input from user. However you could pass a path to the file as an command line argument, and access it using argc and argv arguments of the main function :
int main(int argc, char *argv[])
{
//argv[0] is always name of the program
//argv[1] is the first command line argument
//and so on up to argc-1 (argv[argc-1] is the last argument)
//so, in the simplest form do:
if (argc < 2) return -1; // check if any argument was passed, as pm100 said in comments to this answer.
FILE *f = fopen(argv[1], "rb"); // change "rb" to mode you need
if (f==NULL) return -1; // file could not be opened
// process the file as you need from here
...
}
The alternative approach, reading user input at runtime using fgets could be found here. Then pass the string you got from user as an first argument to fopen.
You can, of course, mix these two approaches (checking if any command-line args were passed, and if not ask for user input) but this probably would be an overkill for a homework.
If you just need to load file from a fixed place in your filesystem, and filename won't change then simply change argv from my example to your filename or path:
int main()
{
const char filename[] = "your_file_name_here";
FILE *f = fopen(filename, "rb"); // change "rb" to mode you need
if (f==NULL) return -1; // file could not be opened
// process the file as you need from here
...
}
I am new to C, I am just trying to read a simple text file I created in C. I made this file by clicking new -> empty file -> saving it to my desired location and then adding the file extension (.txt) the text file holds a sample sudoku board and the full file name is sudokuchar.txt.
The code I have to read from the file and print it is:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fpointer = fopen("sudokuchar.txt", "r");
char input[100];
while(fgets(input,100,fpointer))
{
printf("%s",input);
}
fclose(fpointer);
}
so when i compile the program does not print anything and returns -1. I assume something is wrong with the file i am trying to read from?? if some one could help it would be greatly appreciated.
Always check the return values of fopen and other standard library calls. It's most likely that your file doesn't exist. You can make a nice user friendly error message using errno, just make sure to include errno.h. Overall, your code should work, but you NEED to check the return values of things, because fopen returns NULL if it can't find the file.
FILE *fpointer = fopen("sudokuchar.txt", "r");
if(fpointer == NULL) {
fprintf(stderr, "Error: [Errno %d]: %s\n",
errno, strerror(errno));
return 1;
}
It is advisable to check what file pointer returns. If file pointer returns 0 or NULL then File pointer is unable to point to the file name you had provided. Also you can use this
File *fp = fopen(file name with full path (i.e. /home/chex/read.txt),"r")
Check man fopen
FILE *fopen(const char *path, const char *mode);
I have the following code to find the release of the Linux distribution that I am using.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
return print_osinfo();
}
int print_osinfo()
{
FILE *fp;
extern FILE* popen();
char buffer[128];
int index = 0;
memset(buffer,0,sizeof(buffer));
fp = popen("/etc/centos-release", "r");
if(!fp)
{
pclose(fp);
fp = popen("/etc/redhat-release", "r");
if(!fp)
{
pclose(fp);
return 1;
}
}
while(fgets(buffer, sizeof(buffer), fp)!= NULL)
{
printf("%s\n",buffer);
}
pclose(fp);
return 0;
}
If I run the above code on Ubuntu 14.04 I get the following error.
sh: 1: /etc/centos-release: not found
I fail to understand why it is not trying to open redhat-release and then return -1. Also, is there a way to prevent the above error from being displayed on the screen?
popen is a function more suited for accessing the output of a subprocess than for simply accessing the contents of a file. For that, you should use fopen. fopen takes a file path and a mode as arguments, so all you would need to do is replace your popens with fopens and it should work perfectly.
If you really want to use popen, it takes a shell command as it's first argument, not a filename. Try popen("cat /etc/centos-release","r"); instead.
Now, you might be a bit confused, because both of these functions return a FILE pointer. fopen returns a pointer to the file you passed as an argument. popen, however, returns a pipe pointing to the output of the command you passed to it, which C sees as a FILE pointer. This is because, in C, all i/o is file access; C's only connection to the outside world is through files. So, in order to pass the output of some shell command, popen creates what C sees as a FILE in memory, containing the output of said shell command. Since it is rather absurd to run a whole other program (the shell command) just to do what fopen does perfectly well, it makes far more sense to just use fopen to read from files that already exist on disk.
I am using fopen(3) in C to read file and process it. The file is present in current working directory where the binary exists, but I am unable to read the file (Linux environment / Cygwin environment).
Here is the sample code:
C code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
FILE *inFile;
static char fileName[255];
int process_file(FILE *inFile)
{
char ch;
inFile = fopen(fileName,"r");
if (inFile == NULL)
{
perror(fileName);
exit(1);
}
else
{
// Process file
}
fclose(inFile);
return 0;
}
int main(int argc, char *argv[])
{
printf("Enter filename to process \n");
scanf("%s", fileName);
process_file(inFile);
getchar();
return 0;
}
I have file permissions set to 777 in the current directory. The resulting binary as well as my source code reside in this directory where the input file exits. Why is the file not opened?
Update :
This question was written in few years back and this code could be improved a lot.
1. The process file should accept char * or char array instead of file pointer
2. unused variables can be removed
3. unused libraries or include files can be removed
4. Can make use of argv to accept filename with path from cmdline
5. return instead of exit in process_file and also proper return code instead of returning 0 from process_file.
I should have asked this question little more elaborate...
I had three functions to process the same file, like process_fil1e1(), process_file2() and process_file3() even though I called fclose() in all three functions. Somehow the file handle was not closed that properly or the file pointer pointed to EOF or some undefined behavior. It was not working fine.
When I used a single process file and rewind() together, it worked fine...
Be sure to input file name with its extension. This may cause problems with reading the file.
If you know the extension of the file you can input only the name and after that make the program add the extension. After scanf("%s", fileName); add strcat(fileName, ".txt"); if you want to enter only the name without extension and the file you read has extension .txt.
Your inFile and fileName variables are extern so you don't need to have arguments for the function process_file();, any function can access those variables.
You can change function int process_file(); to void process_file(); and delete return 0, you don't need that.
You have declared the inFile and fileName as global. You should change your function prototype from
int process_file(FILE *inFile)
to
int process_file()
This would at least make your program more clear. Now regarding your problem: It would almost certain be that you are doing something wrong in the input file (like not putting in the file extension) in your input. Remember, you need to pass the complete file name (including the extension which on some systems like Windows (by default) would be hidden). Otherwise, the logic looks correct to me, and it should work fine.
I am trying to pass arguments to the command line in xCode. I have looked up this issue and have found that I need to set the working directory to the path that the file is in. Also I have to add the arguments to the arguments tab under project- edit activeexecutable. I have also done this.
I added michael.txt twice.
/* This file is saved as readtext.c, compiled as readtext */
#include <stdio.h>
void main(int argc, char *argv[])
{
FILE *fin;
char buffer[100];
printf("Michael Mazur\n");
if (argc != 2) {printf("Usage: %s filename\n", argv[0]); exit(1);}
fin = fopen(argv[1], "r");
if (!fin) {printf("Unable to open %s\n", argv[1]); exit(1);}
while (fgets(buffer, 99, fin)) fputs(buffer, stdout);
fclose (fin);
}
I keep reaching the case that there are not 2 arguments being passed. I also ran a little test program and it keeps returning that I only have 1 argument being passed no matter how many I add. Any help?
argv[0] (path to the executable) counts in argc, so if you add michael.txt twice, argc will be 3. A slightly longer description is here. (In general, when something is misbehaving like this, either use a debugger to check the values of all the variables or print them out.)
Make sure both arguments are checked and on separate lines, like this:
Also, in future please mention what version of Xcode you're using; I think from your description it's 3.x, so that's how I answered the question. The user interface varies pretty substantially between versions.