Beginner Q -ARGV and multiple files - c

Good afternoon, Old man trying to learn new tricks here,
I have been given an assignment that I am trying to work my way through but I am stuck as I don't fully understand the argv[]
I have 4 files I want to read from and eventually use malloc and realloc but thats further down.
My initial plan was to try read one file and get it onto the command line. I had it opening but made that many changes that now I'm lost.
Think my problem lies with argv[4] as i dont understand it, when I put 4 it goes into theloop and errors but with 1 it just bombs out.
If someone can point me in the direction I am going wrong here it would be great
Thanks
struct Person { char lname[20]; char fname[20]; int id; };
int i, N;
struct Person *student;
int main(int argc, char *argv[])
{
FILE *outputfile;
printf("Please enter the name of the file to open: ");
scanf("%s", argv[4]);
outputfile = fopen(argv[4], "r") ;
if (outputfile==NULL){
perror(argv[1]);
fprintf(stderr,"Error while opeining file\n");
exit(-1);
}

You don't have to use argv[]. Argv is an array of strings that store the arguments passed in when running the executable. If you run the executable like this: ./a.out, then argv only contains one element, which is the path of the executable itself. If you run the program like this, and you try to access argv[4], it does not give you an error, but if you debug it using GDB, it will output the following: warning: Invalid parameter passed to C runtime function.
You could pass in a file on the command line like this: ./a.out yourfile.txt. In this case, argv[0] will be the path of the executable a.out, and argv[1] will be the string "yourfile.txt".
It might be easier to completely drop the use of argv and store the user input for the filename in a string. You can then pass that string as an argument to fopen. This would look something like this:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
char fileName[30];
char ch;
printf("Please enter a file name\n");
scanf("%s", fileName);
FILE *outputFile = fopen(fileName, "r");
if(outputFile == NULL) {
printf("Could not open %s\n", fileName);
exit(-1);
}
}

Use constants (NAME_LEN) instead of hard-coding magic values.
Prefer multiple lines for your struct. It's easier to read and version control systems prefer lines for diffs.
Avoid global variables.
Do a boundary check using argc (count of elements in argv) before you read argv. argv[0] is the name of your program, argv[1] is the first argument.
Treat argv as read-only, i.e. don't do scanf("%s", argv[4]).
Prefer to initialize variables instead of declaring and assigning a value separately. It's easy to forget setting a variable before use which leads ot undefined behavior. Initialization might be faster, too.
Your file handle is called outputfile but with fopen() you use the mode of r for reading. Either mode should be w or you want to change the variable name to inputfile.
#include <stdio.h>
#include <string.h>
#define NAME_LEN 20
struct Person {
char lname[NAME_LEN];
char fname[NAME_LEN];
int id;
};
int main(int argc, char *argv[]) {
char filename[FILENAME_MAX];
if(argc > 4) {
strcpy(filename, argv[4]);
} else {
printf("filename? ");
fgets(filename, FILENAME_MAX, stdin);
filename[strcspn(filename, "\n")] = '\0';
}
FILE *outputfile = fopen(filename, "w");
if(!outputfile) {
// ...
}
fclose(outputfile);
}
and you would run your program with either:
$ ./a.out dummy dummy dummy output.txt
or
$ ./a.out
filename? output.txt

It sounds as if you are expected to provide 4 file names as command line parameters. In which case you should be doing this:
#include <stdio.h>
int main (int argc, char *argv[])
{
const int files = 4;
if(argc != files+1)
{
printf("Usage: myprog file1 file2 file3 file4");
return 0;
}
FILE* fp [files];
for(int i=0; i<files; i++)
{
fp[i] = fopen(argv[i+1], "r");
...
}
...
}

Related

Open two arguments from command line in C

How would I go about opening only two files from the command line in C? I am working on a Machine Learning Project where the first file has the training data (train.txt) and the second file has the actual data (data.txt). For example, when I compile I am looking for something like this:
./machineLearning train.txt data.txt
Initially, I was thinking it would be something along these lines but was not quite sure if this made sense:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char fileName[100];
while(argc < 2)
{
FILE* fp;
fp = fopen(fileName, "r");
}
}
You find the command line arguments in argv. The first argument is a string at argv[1] and the second at argv[2]. So (after checking argc that you have indeed gotten two arguments), just pass these strings to fopen to open the files:
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE *file1;
FILE *file2;
if (argc < 3) {
/* report that not enough arguments have been given and exit */
}
file1 = fopen(argv[1], "r");
file2 = fopen(argv[2], "r");
/* Check whether file1 or file2 are 0, in case either file could not be opened,
then use the file streams as you require. */
}

Open file using commandline

I'm working on an assignment and I have to open a file from command line upon executing the program.
Example:
program.exe file.txt
However that is not working at all for me. Can someone please tell me what I'm doing wrong? This is the first time I'm working with taking a file as a parameter.
int main(int argc, char **argv) {
int value;
value = fileRead(argv[1]);
}
int fileRead(char argv[]) {
int value;
FILE *fp;
fp = fopen(argv[1], "r");
if (fp) {
fscanf(fp, "%d", &value);
} else {
fprintf(stderr, "Failed to open file!\n");
}
return value;
}
You're mixing up a character and a string. You pass argv[1] to fileRead as argv. Then in fileRead, you do argv[1] again. This effectively does argv[1][1], which just gives the second character of the string. You need to either remove the [1] from in main and then change the argument type, or remove the [1] from fileRead.

How to open and for-loop over the lines of a file using argv argument from command-line (in C)?

Right now, I have a main function that looks like (argv[2] is the file I want to loop over, from the command-line)
int main(int argc, char * argv[]) {
FILE *thisfile;
thisfile = fopen(argv[2], "r");
while ....
}
I want to eventually be able to loop over each line of the file, argv[1] and see if any of the lines contain a string, which is argv[1]. I know of the C operations like fgets, but I am not sure how to use them. So for now, outputting each line of the file is enough, but after I'd like to see if each line contains a string. I am very new to C, any help is appreciated!
the first question is easy,the code just like
#include <stdio.h>
#define MAXLINE 1024
int main(int argn, char *argv[])
{
FILE *fp;
char line[MAXLINE];
fp = fopen(argv[2], "r");
while(fgets(line, MAXLINE, fp) != NULL)
printf("The line is:%s\n", line);
return 0;
}
but your second question(find a string in one line) has many ansower,it's pattern recognize,if you want ,you can google kmp.

Why am I segfaulting?

I'm very new to C, I am attempting to read the contents of one file character by character and output them to the stream. But even with my fopen() command commented out I receive segfault (core dumped).
I must run a command: ./a.out < testWords.in > myOut.txt to execute my file properly.
Here is what I have so far:
#include <stdio.h>
void main(char *fileName[])
{
printf("filename is %s.\n",fileName[0]);
//Get file based on a string inputed
FILE *fp=fopen(fileName[0],"r"); //Fetches our file as read only
char ch;
int lineCount = 0;
int wordCount = 0;
int charCount = 0;
//Failed to find/open file. NULL character.
if (fp == 0) printf("Woops! Couldn't open file!\n");
//While not at end of file, grab next char.
else while( (ch=fgetc(fp)) != EOF)
{
if (ch == '\n') //on newline
{
//Prints (charCount,wordCount)\n lineCount:
printf("(%d,%d)%c%d:",charCount,wordCount,ch,lineCount);
charCount = 0;
lineCount += 1;
}
else printf("%c",ch); //mirrors char.
}
fclose(fp); //Closes file (gotta be tidy!)
}
You can't just invent a way to call main. You need to use one of the standard ways, like this:
int main(int argc, char *argv[])
{
if (argc < 2) {
fprintf(stderr, "Missing filename\n");
return -1;
}
FILE *fp = fopen(argv[1], "r");
// ...
}
And note that argv[0] contains the program name (if available; if not it contains an empty string).
Your program segfaulted because you received the int argc argument into your char *filename[] parameter. If you ran the program with a single command line parameter, the value passed in as the first argument would have been 2, which is not a valid pointer value. The expression filename[0] dereferences that address and causes a segfault.
Any time you get a segfault in C, you should smell a bad pointer or address in an argument list. In this particular case., the signature of main is always int main(int argc, char** argv). Yours isn't.
What you want is
int main(int argc, char ** argv) {
...
FILE * fp = fopen(argv[1]); // Quiz: why argv[1]? What's argv[0]?
You're getting away with it in the compiler because, basically, luck.
I also notice in your example call, there's actually no argument in the argument list, because you're using redirection.
Use:
int main(int argc, char* argv[])
And use argv[1] as fileName.
Main function must receive always that two parameters.

How do I define and pass in a file name to fopen() from command line?

I have the following program that writes a user's input to a file. Currently the file to be written to is predefined; however, I was wanting allow the user to define the file name from command prompt. What would be the best way to add this functionality? I am having trouble getting my head around how I would make the string entered by the user an argument in the fopen() function. Should I use scanf() or create another getchar() while loop store the chars in an array and then create a variable as the argument of fopen() or something?
#include <stdio.h>
int main()
{
char c;
FILE *fp;
fp = fopen("file.txt", "w");
while ((c = getchar()) != EOF)
{
putc(c, fp);
}
return 0;
}
That's what the arguments to main are for:
#include <stdio.h>
int main(int argc, char **argv)
{
char c;
FILE *fp;
if (argc >= 2)
fp = fopen(argv[1], "w");
else fp = fopen("file.txt", "w");
while ((c = getchar()) != EOF)
{
putc(c, fp);
}
return 0;
}
If you followed this, you might wonder what is in argv[0]. That's where the program name is. Some operating system environments put the full path to the executable file there. Others put only the program name. Others still put what was typed.
For the command ../../bin/someprogram
on Windows, argv[0] is "C:\\Documents and Settings\\User\bin\\someprogram.exe"
on Linux/bash, argv[0] is ../../bin/someprogram
on Ultrix/csh, (I think) argv[0] is /home/username/bin/someprogram
Use argc and argv
#include <stdio.h>
int main(int argc, char **argv)
{
char c;
FILE *fp;
if(argc < 2){
printf("Usage : ./a.out <filename>");
exit(0);
}
fp = fopen(argv[1], "w");
while ((c = getchar()) != EOF)
{
putc(c, fp);
}
return 0;
}
Define main like this:
int main(int argc, char *argv[]) {
And then use argv: an array of the command-line arguments. argv[0] is the name of the command as entered at the command line, argv[1] is the first argument.
fp = fopen(argv[1], "w');
You probably want to check that argc > 1 to avoid an out-of-bounds array access.
There are many functions to read in strings; fgets and scanf, for example. The problem is that you need to know the max number of characters that you want to read in before-hand. If this is ok for you, then use one of those. If not, then you'll have to write your own function to read in a dynamic string, like here.

Resources