If someone can help me get past this roadblock that would be amazing. I am trying to open a text file called "inputfile.txt" and I can not! Every example I have looked at has worked fine, but when I try to use it, the file returns null and I get a segmentation fault.
Note, this is prior to error checking
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE *inputPtr;
inputPtr = fopen(argv[2], "r");
fclose(inputPtr);
}
I realized that I "goofed" slightly, when I first created the text files on my desktop I titled it "inputfile.txt", but it was saved as "inputfile.txt.txt" as odd as that is!
Well the first big problem is that you do not check the value of argc. This value is set to the number of arguments that were passed to the programm. By default argc is at least 1, because 1 argument is always passed. If you pass any additional arguments, argc must be greater than 1. In your case, i guess it should be 2.
The second problem comes from the first. The numbering of array elements in C starts from 0, so if your programm accepts argc arguments, argv which keeps the arguments will have argc elements, BUT!!! the last element will have an index of argc-1. By default, if no additional arguments were passed only argv[0] exists and it is the name of the programm, it is also always passed, hence argc is always at least 1.
In your case, if argc==2, then argv[2] simply does not exist, only argv[0], and argv[1] exist. And when you pass one argument to the programm, it will be kept in argv[1]. That means that this line inputPtr = fopen(argv[2], "r"); should be changed to this inputPtr = fopen(argv[1], "r");. Also there should be a check of argc at the beginning of the programm. soome thing along the lines of
int main(int argc, char *argv[])
{
if(argc!=2)
{
printf("Wrong number of arguments\n");
return -1;
}
.....
}
before accessing anything beyond argv[0] (which is always available)
the code must check the value of argc to assure the command line parameter actually exists.
Note; in C, array indexs start from 0 through (count of array entries -1).
So if argc is 2, then there is only one command line parameter and:
argv[0] is the executing program name
argv[1] is the first parameter.
argv[2] is a NULL pointer.
so using argv[2] is accessing address 0 and will result in
undefined behaviour
lead to a seg fault event
Related
I'm writing a code that appends text to a file.
It uses fopen in the beginning of WriteToFile so even if the file does not exist, it creates it.
But, what happens when I enter no file at all? no arguments at all? Just ./a.out?
Segmentation fault.
I don't know why, it seems to me I did everything fine to avoid any problems.
int main(int argc, char **argv)
{
char file_name[30] = "file.txt";
printf("%s",file_name); /* for debugging : doesn't print it */
if (0 != argc)
{
strcpy(file_name, argv[1]);
}
WriteToFile(file_name);
}
OR
(in case I can't really put a string literal into char array):
char file_name[30];
if (0 == argc)
{
strcpy(file_name, "file.txt");
}
else
{
strcpy(file_name, argv[1]);
}
For both of the cases i'm getting
Segmentation fault (core dumped)
if (0 != argc)
The argc value is normally(a) the count of arguments including the program name. Hence, running ./a.out will have an argc of one rather than zero. And, since argv[argc] is usually NULL, dereferencing it is not going to end well :-)
If you want to ensure another argument is available, you can use:
if (argc > 1) { // Have both argv[0] AND argv[1].
nowSafeToUse(argv[1]);
}
In more detail, the C11 standard states:
If they are declared, the parameters to the main function shall obey the following constraints:
The value of argc shall be nonnegative.
argv[argc] shall be a null pointer.
If the value of argc is greater than zero, the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup. The intent is to supply to the program information determined prior to program startup from elsewhere in the hosted environment. If the host environment is not capable of supplying strings with letters in both uppercase and lowercase, the implementation shall ensure that the strings are received in lowercase.
If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment. If the value of argc is greater than one, the strings pointed to by argv[1] through argv[argc-1] represent the program parameters.
The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination.
As an aside regarding this line:
printf("%s",file_name); /* for debugging : doesn't print it */
If this is not printing, it's probably because standard output is line buffered (default if it's determined to be an interactive device, otherwise fully buffered).
By not outputting a \n at the end, the characters are probably still sitting in a buffer somewhere, ready to be written. The crash will probably kill off the process without flushing the buffer. So a simple solution may be just to use one of:
printf("%s",file_name);
puts(file_name);
As another aside, you're going to get into trouble if the filename you enter is larger than 29 characters since it will overflow file_name, allowing for the \0 at the end as well.
A better approach may be just to use either your default string or argv[1] directly (without copying), something like:
int main(int argc, char **argv) {
char *file_name = (argv > 1)
? argv[1]
: "file.txt";
printf("%s\n", file_name); // for debugging : probably does print it :-)
WriteToFile(file_name);
}
(a) Not required by the standard since it allows for implementation-specific differences, but it's the usual case. Specifically, the phrase:
... which are given implementation-defined values by the host environment prior to program startup. The intent is to supply to the program information determined prior to program startup from elsewhere in the hosted environment.
pretty much means it can do whatever it wants :-)
A related answer (though a non-duplicate question) can be found here.
When argc is 1, argv is treated as an array of 2 pointers to char. The first is a valid pointer (typically to the program name), the second is NULL.
argv[1] accesses the second element of argv. With no arguments supplied, argc will be 1 and argv[1] will be NULL. You're therefore dereferencing a NULL pointer.
The condition 0 != argc should instead be argc >= 2 or argc > 1, and the condition 0 == argc should be argc < 2 or argc <= 1.
You have to account for the program's name so you should write if (argc >= 2) instead. See the man
The value of the argc argument is the number of command line arguments. The argv argument is a vector of C strings; its elements are the individual command line argument strings. The file name of the program being run is also included in the vector as the first element; the value of argc counts this element. A null pointer always follows the last element: argv[argc] is this null pointer.
argv[1] means index 1 but in C you start at index 0.
Fixed code
int main(int argc, char **argv)
{
char file_name[30] = "file.txt";
printf("%s",file_name); /* for debugging : doesn't print it */
if (argc >= 2)
strcpy(file_name, argv[1]);
else
return 1; // exit program with error code.
WriteToFile(file_name);
return 0; // exit with success
}
I'm trying to input only one filename from command line. Then I want to use an If statement to compare the filename to 4 different names I'm expecting to see. If I don't get one of the 4 expected file names then I need to print it back to the user with what was inputted and then exit the program safely.
int main(int argc, char *argv[])
{
....
}
I've been trying a lot of different methods of getting this done, but I just can't figure it out. I was thinking maybe the way I take the input argument is wrong. Any help would be greatly appreciated.
-edit
I just want to be clear I don't want you to be a leech and solve the question I have for me. Just at least point me in the correct direction. I can't figure how to make a for loop work with the filename.
for(argv == "UnexpectedFile.csv"){
printf("this is an unexpected file: %c", argv[1]);
}
You could use strcmp() from string.h to compare strings like
strcmp(argv[1], "unexpectedfile.csv");
It returns 0 when the strings are equal.
If you have the 4 file names in as an array of strings, say expectedFile, do
for(i=0; i<4 && strcmp(argv[1], expectedFile[i])!=0; ++i);
If the value of i is the total number of file names (ie, 4) after this loop, argv[1] is an unexpected file.
Otherwise, value of i would be the index of the file name string in the expectedFile array.
The command line arguments are stored in the 2-dimensional char array argv.
argv[0] would be the name of the executed file. The arguments you give start only from argv[1] onwards.
argc will have the total number of command line arguments including the file name stored in argc. So if there are 'no' arguments, argc would be 1.
In your case the file name is the only argument, so argc would be 2.
You must check if argc is at least 2 before you access argv[1] to prevent the program from accessing argv[1] when it isn't there.
(You do not ask for complete code solution (and do not provide enough of your code for that). So here are the pointers in the right direction you want.)
The comparison you do with a simple pointer == pointer does not really compare the content of the strings. That is what e.g. strcmp () is for, as proposed by #user3629249.
And in order to print out what was given as commandline argument, you should use "%s\n".
And in order to set up a for loop, you will have to do the syntax right: for(init assignment; condition; step operation).
(If you need more help, you will have to provide more details on what behaviour you get and what you do not like about it. Currently your code looks more like compiler errors, which you did not quote, than a problem with the behaviour goal...)
write c program that accepts one command line argument (your first name) and prompts the user for user input (your last name), then print ""Welcome to operating systems, "" to the screen.
Can anyone help me with this question? I know its using something like this from the below, but I dunno how to print out the thing? Can anyone help by giving the full answer? Thanks in advance.
int main (int argc, int *argv[])
argc is an integer that represents the number of command line arguments passed in to the program. It is the argument count, hence the name. *argv[] (or **argv depending on developer preference) represents the actual arguments. The proper name for argv is argument vector, which makes sense if you're familiar with that particular data type.
The first argument passed in, argc = 1 is the program's name. Argc is always at least one because argv will always contain at a minimum the name of the program.
To answer your question, you need to pass in a second command-line argument, argc = 2, where argv[1] equals the user's first name. We can accomplish that like this:
int main(int argc, char** argv)
{
// This line will print out how many command line arguments were passed in.
// Remember that it will always be at least one because the name of the program
// counts as an argument.
printf("argc: %d", argc);
// Remember that you want the second argument in argv,
// so you have to call argv[1] because arrays in C
// are 0-index based. Think of them as offsets.
printf("\nWelcome, %s", argv[1]);
return 0;
}
This should get you started. All you need to do now is write the code to read the string from the standard input and output it to the console.
So, I noticed that my argc is always 1 as I will always get the message Error: missing command line arguments!, but as stated in code I am using argv[1] and argv[2] to read the files names.
Shouldn't automatically argc be 3 in this case, and to be able to pass that error?
Notes:
If I am not using if (argc < 2) statement, after I enter the name for the output file my program crushes.
For the input file I already have this one created in the project folder, so I just enter the name of that file.
This is the code:
#include <stdio.h>
#include <stdlib.h>
FILE *IN, *OUT;
int main(int argc, char* argv[])
{
if (argc < 2)
{
printf("Error: missing command line arguments!\n");
return 1;
}
printf("Enter the name of the file with the input data: ");
scanf("%s", argv[1]);
printf("\nEnter the name of the file for the output data: ");
scanf("%s", argv[2]);
IN = fopen(argv[1], "r");
OUT = fopen(argv[2], "w");
fclose(IN);
fclose(OUT);
return 0;
}
You're complete mis-understanding the purpose of argc and argv. They are supposed to receive the supplied command line argument (program parameters) before the program startup, not supposed to hold the scannned input at runtime.
Quoting C11, chapter ยง5.1.2.2.1,
If they are declared, the parameters to the main function shall obey the following
constraints:
โ The value of argc shall be nonnegative.
โ argv[argc] shall be a null pointer.
โ If the value of argc is greater than zero, the array members argv[0] through
argv[argc-1] inclusive shall contain pointers to strings, which are given
implementation-defined values by the host environment prior to program startup. The
intent is to supply to the program information determined prior to program startup
from elsewhere in the hosted environment.
and
If the value of argc is greater than zero, the string pointed to by argv[0]
represents the program name; argv[0][0] shall be the null character if the
program name is not available from the host environment. If the value of argc is
greater than one, the strings pointed to by argv[1] through argv[argc-1]
represent the program parameters.
To elaborate, when a program is invoked like
./a.out three total arguments
then, in your program
argc will be 4
argv[0] will be ./a.out
argv[1] will be three
argv[2] will be total
argv[3] will be arguments
argv[4] will be NULL (see the property for argv[argc] above)
(To generalize, argv[1] - argv[argc-1] will hold the supplied arguments, argv[argc] will be NULL)
You don't need to explicitly scan the input, those values will be populated from the host environment.
On the other hand, you cannot just invoke the program like
./a.out
and exptect argc to be 3 (or any other value, other than 1, for that matter) and argv[1] - argv[n-1] to be valid because at compile-time the invokes program has no way to know that you plan to supply some values at runtime. It's not clairvoyant.
Why will this simple function cause seg fault?
int main(int argc, char** argv) {
FILE* file1;
file1 = fopen(argv[argc + 1], "wt");
fclose(file1);
}
Your fopen() is failing to open the file, so fp is NULL, so fclose() is legitimately objecting by crashing. Check the return from fopen().
Also, by definition, argv[argc] == 0 and argv[argc+1] is beyond the end of the array. In practice, on Unix systems, it will often be the name=value of the first environment variable, but it is unlikely to be a valid filename and most certainly wasn't obtained legitimately.
If your program is invoked as:
./a.out file.txt
then the file name is argv[1]; the string pointed at by argv[0] is the name of the program, a.out give or take path information, and argc == 2 and argv[2] == 0. Don't forget to check that argc == 2 before trying to open the file.
Always check return statuses, especially from 'known to fail' function such as fopen(). And print the name that you're opening - it would have told you a lot about your problem - after checking that argc is set to a value you expect.
You access two elements after the last element of argv. You also don't check the return value of fopen(), both could cause the segfault.