reading data from a file into an array error in C - c

I am trying to read from a file specified in a command prompt through terminal using the line program < file.txt and then print it again to check it works. I get the error Segmentation fault: 11, I'm not sure if my file is opening correctly in my program.
This is the code so far:
#define MAX 1000
int
main(int argc, char *argv[]) {
FILE *fp;
double values[MAX];
fp = fopen(argv[1], "r");
fscanf(fp, "%lf", values);
printf("%f\n", *values);
fclose(fp);
return 0;
}
Any help or feedback would be greatly appreciated.

You should execute your program like
./program file.txt

I'm not sure if my file is opening correctly in my program
Then you should really test for it, you are getting a segfault because fopen is returning NULL.
#include <stdio.h>
#define MAX 1000
int
main(int argc, char *argv[]) {
FILE *fp;
double values[MAX];
fp = fopen(argv[1], "r");
if (!fp) {
printf("Invalid file name \n");
return -1;
}
fscanf(fp, "%lf", values);
printf("%f\n", *values);
fclose(fp);
return 0;
}
fopen is NULL because you are invoking the program in the wrong manner, < and > are a re-directions which can be useful but is not what you are trying to do in this case, correct way to invoke it is to simply pass it the arguments directly.
./program input.file

Yeah, either:
1) check the way you're invoking it, i.e,
check if the 'program' is an executable file, you can make it executable using chmod command in linux
check if the path to 'program' or 'file.txt' is correct
2) (I'm not sure of this): check if the content of 'file.txt' is of the right content. (I don't think it should affect to the extent that it causes a segmentation fault, but still, check it.)

Related

how to write a command line to a file in c

I'm having issues with writing this command line to a file and it's suppose to output to the screen. To me, my code looks like it should work but I'm at a complete loss (this is my first time programming in C)
Print one line describing your program
Open the first parameter as a file for writing. If no parameter is provided, write to the stdout handle
Using a loop, save the contents of the array of string pointers passed as a parameter to the main function into the file open for writing. This is usually the variable named argv.
int main(int argc, char *argv[])
{
FILE *fp;
int i;
printf("Output supplying 'multiple arguments' to this program");
fp = fopen(argv[1], "w"); //Write to file
if(fp==NULL)
{
fp = stdout;
}
for(i=0;i<argc;i++)
{
fprintf(fp, argv[i]);
}
printf("The number of arguments printed %d", argc);
return 0;
Any help provided would be greatly appreciated!
Don't ever use dynamic format strings in C. This opens you up to an extensive set of bugs, several of them security-sensitive. Instead, pass a format string that indicates your intent, like so:
for(i=0;i<argc;i++)
{
fprintf(fp, "%s\n", argv[i]);
}

How to read files in C, in this format ./filec <input.in> <output.myout>

im currently doing a project which works with input files.
The code is doing everything that i want, and its fully correct, the problem is the way im reading the file.
FILE *fp;
fp = fopen (argv[1], "r");
in the terminal im using ./filec input.in, and everything gets printed correctly in the terminal, but i have to open the file in this way:
./filec < input.in > < output.myout > and im not sure what does that entail.
Thank you, and sorry for the poor english
Your argv[1] would have the input file, and yourargv[2] would have the output file.
A basic beginning layout for you to work on would be:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
if (argc != 3)
{
exit(EXIT_FAILURE); //If there are not three arg, terminate the program.
}
FILE *fp_read, *fp_write;
fp_read = fopen(argv[1],"r");
fp_write = fopen(argv[2],"w");
//Do whatever you want with it.
fclose(fp_read);
fclose(fp_write);
return 0;
}
I assume you have a typo and you actually mean:
./filec < input.in > output.myout
Basically, this means you are letting the shell do all the work for you, and your code can simply read from stdin and write to stdout. You might try:
fp = argc > 1 ? fopen(argv[1], "r") : stdin;
It could be you misunderstood the --help option, the first notation you describe is, for commandline arguments, the correct one. "" is just a notation that is used, meaning that you can change the name of the parts between <>.
Anyway, if you really need to use that notation to call your program, you could make a new array containing the argv[1] without <>.
pseudo code:
char newFilename[20];
//skip first and last character (if needed, changes values to skip first two and last two chars
for(i = 1; i < argv[1].length - 2; i++){
newFilename[i - 1] = argv[1][i];
}
fp = fopen (newFilename, "r");
Note that the < and > characters are interpreted as file redirection operations, so you should do (in this case) ./youprogram "< file.in >" "< file.out >"
First, read about fopen(3) and stdio(3)
You want to read from stdin
When calling fopen you always should check for failure, e.g. (after having tested that argc>1, assuming you defined int main(int argc, char**argv) as is conventional!)
FILE *fp = fopen (argv[1], "r");
if (!fp) {perror(argv[1]); exit(EXIT_FAILURE); };
so you probably want:
FILE *fp = NULL; // I prefer always initializing variables
if (argc>1) {
fp = fopen (argv[1], "r");
if (!fp) {perror(argv[1]); exit(EXIT_FAILURE); };
}
else fp = stdin;
If you invoke your program as ./myprog < someinput.txt > someoutput.txt then everything you printf, putchar or send to stdout goes into someoutput.txt, and stdin is the someinput.txt. Generally the redirection is done externally (by the shell on POSIX systems)

Writing C program to create a 1 MB file on Linux and getting Segmentation Fault

I'm trying to write a simple C program for Linux that will generate a 1 MB file but I can't get this code to work. When I try to run it I get a seg fault error message thrown and I'm not really sure where it's going wrong. I do have a hunch that it is with fseek though:
#include <stdio.h>
int main(int argc, char *argv[])
{
FILE *fp;
fp = fopen(argv[0], "w");
fseek(fp, 1000000 - 1, SEEK_SET);
fputc('\0', fp);
return 0;
}
Can anyone point me in the right direction?
argv[0] is the name of your binary. You want to use argv[1] as your filename.

Segmentation fault before first line of code

I am working on a simple C program to open a file and read some data from it. There are no compile errors, but when I run the program on a certain file, I get a "Segmentation Fault: code dumped" error. I inserted a print statement at the very top of my code, and it does not get run. Is it possible to get a segmentation fault when you haven't done anything yet?
#include <stdio.h>
int main(int argc, char **argv)
{
printf("%s", "Made it to here!");
FILE *fp;
char input[100];
fp = fopen(argv[1], "r+b");
fgets(input, sizeof(input), fp);
printf("%s", input);
fclose(fp);
return(0);
}
This works when I run it on the text version of itself, it prints out the first line. However, when I run it on another file, texttest.vmf, I get the segmentation fault and the first print doesn't execute. VMFs are Valve Map Files, but they're in standard text format. This file is about 3.7 KB large. Any ideas?
It is not necessary that your code fails before printf: the call to printf may have succeeded, but because the output to console is buffered, the program may have crashed before the output has been written to the screen.
Adding \n to the output string causes console buffer flush. If you are looking to debug by printfs, you should always add \n to the end of your format string.
Your fopen call is likely failing. Try checking the return value before you attempt to use fp:
FILE *fp;
char input[100];
if((fp = fopen(argv[1], "r+b") == NULL) {
fprintf(stderr, "ERROR: Cannot open file.\n");
return 1;
}
Make sure to add #include <stdlib.h> for use of the NULL macro.

How to run c program and give input in same line

I'm new to C and I'd like to ask about running a C program and supplying input at the same time.
What I would like to do is run a program (ex. fileOpener) and also state which file to open
./fileOpener < filename1
I've tried it already and it works fine, but what do I use to know what filename1 is? That way I can open the file with
fp = fopen(filename1, "r")
Thanks.
Edit: OK, I'll try to explain a bit more. If there wasn't a "<" then I could just use command line arguments as I have done before, but when I tried it with the <, it didn't work
Specifically: fileOpener code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
printf("%s", argv[1]);
}
when I use ./fileOpener < filename1 the output is ./fileOpener
I used gcc -o fileOpener fileOpener.c as the compiler
int main(int argc, char *argv[])
You can name them whatever you want, but these are the normal names.
argc is non-negative. It gives the number of useful elements in argv.
If argc is positive, argv[0] contains the program name. Then argv[1] through argv[argc - 1] point to character arrays that contain the program's command line arguments.
For example, if I run a program at the command line, such as
unzip filename.zip
argc will equal 2; and argv[0] will compare equal to "unzip"; and argv[1] will compare equal to "filename.zip".
Source
You can't do that, if you use redirection (i.e. "< filename") the file is opened by the system. You could discover the name, but it's non-portable, and anyway useless since the file is already open. Just use stdin instead of fp, and you need not use fopen() (nor fclose()):
int main()
{
char buffer[1024];
// fgets() reads at most 1024 characters unless it hits a newline first
// STDIN has been already opened by the system, and assigned to data flowing
// in from our file ( < inputFile ).
fgets(buffer, 1024, stdin);
printf("The first line of input was: %s", buffer);
}
A different approach is to use arguments:
int main(int argc, char **argv)
{
FILE *fp = NULL;
char buffer[1024];
if (argc != 2)
{
fprintf(stderr, "You need to specify one argument, and only one\n");
fprintf(stderr, "Example: %s filename\n", argv[0]);
// Except that argv[0], this program's name, counts.
// So 1 argument in command line means argc = 2.
return -1;
}
printf("I am %s. You wanted to open %s\n", argv[0], argv[1]);
fp = fopen(argv[1], "r");
fgets(buffer, 1024, stdin);
printf("The first line of input was: %s", buffer);
fclose(fp); fp = NULL; // paranoid check
return 0;
}
You need setup your program to take a command line argument. Here's a good tutorial that solves your exact question:
http://www.cprogramming.com/tutorial/c/lesson14.html
A program's main function in C has two arguments:
int main(int nArgs, char *pszArgs[]) {}
That first argument tells the program how many parameters were passed onto the program when you ran it. Usually, this will just be 1, because it includes the program's name.
The second argument is a table of strings, which can be accessed thus (the program below prints the parameters given to it):
int main(int nArgs, char *pszArgs[])
{
int i = 0;
while (i < nArgs)
{
printf("param %d: %s\n", i, pszArgs[i]);
i++;
}
return 0;
}

Resources