I'm trying to read data from a text file and copy them into an array, but my code doesn't work. This is the code:
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
FILE *data;
data = fopen(argv[1], "r");
.......
fclose(data);
}
and when I replace
data = fopen(argv[1], "r");`
with
data = fopen("(the file name)", "r");
it works.
this is the full code
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
i=0;
FILE *data;
data = fopen(argv[1], "r");
while (!feof(data)) {
fscanf(data, "%i", &aa[i]);
i++;
}
fclose(data);
printf("%i\n", aa[0]);
}
and the text file is
3
2 1
2 2
2 3
You should always write basic error checking code for anything which might reasonably fail, e.g.:
#include <stdio.h>
#include <errno.h>
int main(int argc, char *argv[])
{
int i;
FILE *data;
if (argc < 2)
{
fprintf(stderr, "Missing arguments: %s\n", usage);
exit(1);
}
data = fopen(argv[1], "r");
if (data == NULL)
{
fprintf(stderr, "fopen('%s') failed, errno = %d, argv[1], errno);
exit(2);
}
.......
fclose(data);
return (0);
}
This way if fopen fails then (a) you won't crash and (b) you will get some useful info as to why the file was not opened.
You might be passing the file which is not available in the current directory.
Give the valid file directory with file name as argument
check for null after 'fopen'
compile with gcc -g -Wall main.c
and use gdb debugger to identify the error
You should pass filename while running the code.
./a.out file.txt.
If file.txt does not exist then it will throw error as segmentation fault.
Try this code, its working
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
int j = 0;
int aa[100]; //declare an int array to store the data, as you are retrieving using %i
i=0;
FILE *data;
data = fopen(argv[1], "r");
while (!feof(data)) {
fscanf(data, "%i", &aa[i]);
i++;
}
i--;
fclose(data);
for(j; j < i; j++)
printf("%i\n", aa[j]);
}
in file.txt give whatever data you are giving.
and while running pass ./a.out file.txt
See to it that file.txt is in same folder or give whole path
Related
I'm using the following code below and I'm receiving a Thread 1: EXC_BAD_ACCESS (code=1, address=0x68) error. What are some ways I can execute this better? I'm simply loading a txt file that has roughly 500000 numbers and they are each on a new line. I've looked at a few resources how to do this, but I end up with these oddities. I'm hoping a c guru can help me out.
#include <stdio.h>
#include <time.h>
#include <limits.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#define COUNT_ARRAY_LENGTH 10
#define MAX_NUMBER 500001
int *load_file(){
FILE *file;
file = fopen("somefile.txt", "r");
int a[MAX_NUMBER];
int i=0;
int num;
while(fscanf(file, "%d", &num) > 0) {
a[i] = num;
i++;
}
fclose(file);
return a;
}
int main(int argc, const char *argv[])
{
int *a;
a = load_file();
for(int i = 0; i < MAX_NUMBER; i++){
printf("%d\n", a[i]);
}
return 0;
}
Converting comments into an answer.
My immediate guess would be that you're failing to open the file — an error you don't check for and must always check for. Files go AWOL, or the program is run from the wrong directory, or they have the wrong permissions.
if (file == NULL)
{
fprintf(stderr, "Failed to open file '%' for reading\n", "somefile.txt");
exit(EXIT_FAILURE);
}
The repeated literal for the file name shows why you should never pass a string literal as the file name to fopen(); you should have a variable so that you can report the file name in the error message too, without repeating yourself.
const char *filename = "somefile.txt";
if ((file = fopen(filename, "r")) == NULL)
{
fprintf(stderr, "Failed to open file '%' for reading\n", filename); n.
exit(EXIT_FAILURE);
}
In fact, you should probably pass the name of the file to be loaded to the load_file() function so that you can more easily change it (by command line arguments, for example). That is as well as passing the array, and the size of the array. That gives you a more generic function, one more easily adapted to other uses.
You could also #include <errno.h> and #include <string.h> and use strerror(errno) to print the system error message to give more help to the user (but knowing the file name is a huge step in the right direction).
Also, you should have while (i < MAX_NUMBER && fscanf(file, "%d", &num) > 0) so you don't overflow the array.
Also, you're returning the address of the local array in load_file() — you can't do that safely. Define the array in main() and pass the pointer as a parameter. Your main() also assumes that the array was filled. Revise load_file() to return how many numbers were loaded so you don't access unloaded numbers.
Putting all those changes together might yield:
#include <stdio.h>
#include <stdlib.h>
#define MAX_NUMBER 500001
static size_t load_file(const char *filename, size_t arrsiz, int *array)
{
FILE *file;
if ((file = fopen(filename, "r")) == NULL)
{
fprintf(stderr, "Failed to open file '%s' for reading\n", filename);
exit(EXIT_FAILURE);
}
size_t i = 0;
int num;
while (i < arrsiz && fscanf(file, "%d", &num) > 0)
array[i++] = num;
fclose(file);
return i;
}
int main(void)
{
int a[MAX_NUMBER];
size_t num = load_file("somefile.txt", MAX_NUMBER, a);
for (size_t i = 0; i < num; i++)
printf("%d\n", a[i]);
return 0;
}
That's been compiled but not run.
You could process a command-line argument like this:
int main(int argc, char **argv)
{
if (argc > 2)
{
fprintf(stderr, "Usage: %s [filename]\n", argv[0]);
exit(EXIT_FAILURE);
}
const char *filename = (argc == 2) ? argv[1] : "somefile.txt";
int a[MAX_NUMBER];
size_t num = load_file(filename, MAX_NUMBER, a);
for (size_t i = 0; i < num; i++)
printf("%d\n", a[i]);
return 0;
}
Or you could allow more than one argument and iterate over them all.
Sometimes, it's better to do the file opening and closing in the main() and pass the open file stream to the function. You can then read from stdin if there are no command-line arguments. The options are legion!
I have the following code and when I try to run it, I get the following warning:
warning: variable 'myfile' is uninitialized when used here [-Wuninitialized]
myfile = fetch_file(myfile, argc, argv);
note: initialize the variable 'myfile' to silence this warning
FILE *myfile;
I have been trying to find out how to fix the warning but haven't been successful.
#include <stdio.h>
#include <stdlib.h>
#define LINE_SIZE 300
FILE * fetch_file(FILE *myfile, int argc, char *argv[1])
{
if (argc == 1)
{
printf("Error, not enough commandline arguments.");
exit(0);
}
myfile = fopen (argv[1], "r");
if (myfile == NULL)
{
printf("\nNo file named %s was found.", argv[1]);
exit(0);
}
else
{
printf("%s was successfully opened", argv[1]);
}
return myfile;
}
void print_file(FILE *the_file, char *line, int size)
{
int count = 0;
while (fgets(line, size, the_file) != NULL)
{
printf("%s", line);
count++;
}
fclose(the_file);
printf("\nThere are %d lines\n", count);
}
int main (int argc, char *argv[])
{
FILE *myfile;
char line[LINE_SIZE];
myfile = fetch_file(--> myfile <-- , argc, argv); <----------- (warning)
print_file(myfile, line, LINE_SIZE);
return 0;
}
Ps: I'm fairly new to asking questions on this website, so if there is any way I can improve my questions and code, feel free to criticise me...
You want this:
FILE *fetch_file(int argc, char *argv[1])
{
if (argc == 1)
{
printf("Error, not enough commandline arguments.");
exit(0);
}
FILE *myfile = fopen (argv[1], "r");
...
}
int main (int argc, char *argv[])
{
FILE *myfile;
char line[LINE_SIZE];
myfile = fetch_file(argc, argv);
...
}
It is pointless to pass the myfile parameter to fetch_file.
The reason for the warning is that you pass an uninitialized value to a function:
This simple code reproduces this exact problem:
int foo(int bar)
{
bar = 2;
return bar * 2;
}
int main (int argc, char *argv[])
{
int kwork; // kwork is not initialized
foo(kwork); // here you pass an uninitialized value
// which the foo function cannot use in a useful manner
}
I wanna do this:
Progam1 | Program2
I wanna use the output of the first program as input(stdin) for the program2 to do some calculations.
for now this is what i have in program 2
int main(int argc, char *argv[]) {
char userInput[100];
int num[100];
FILE *cmdLn = stdin;
if (argc > 2) {
fprintf(stderr, "Usage: %s [<file>]\n", argv[0]);
exit(EXIT_FAILURE);
}
if (argc == 2) {
cmdLn = fopen(argv[1], "r");
if (!cmdLn) {
perror(argv[0]);
exit(EXIT_FAILURE);
}
}
int numInput[100];
for (int i = 0; i < 100; i++) {
fscanf(cmdLn, "%d", &numInput[i]);
printf("%d\n", 2*numInput[i]);
}
if (cmdLn != stdin) {
fclose(cmdLn);
}
exit(EXIT_SUCCESS);
}
program 1 just creates several numbers per row. I want to use those numbers in program 2 to double them and print the result.
What am I missing here?
I am reading from with fgets from *file which is getting input from stdin
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
char userInput[100];
int numInput[100];
FILE *file = stdin;
if (argc > 2) {
fprintf(stderr, "Usage: %s [<file>]\n", argv[0]);
exit(EXIT_FAILURE);
}
if (argc == 2) {
file = fopen(argv[1], "r");
if (!file) {
perror(argv[0]);
exit(EXIT_FAILURE);
}
}
int num[100];
while (fgets(userInput, sizeof(userInput), file))
{
num[i] = atoi(userInput);
printf("%d\n", 2*num[i]);
i++;
}
if (file != stdin) {
fclose(file);
}
exit(EXIT_SUCCESS);
}
the shell redirection works, but not exactly how I want.
Program 1 gives me 10random int numbers.
when I get 10 different numbers from program 1 and pipe its output to program 2 I get new 10 random values and not the output of program 1 before.
program 2 should calculate those(e.g. multiply by 2).
Maybe the problem lies in program 1:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXNUM 1000
int main(int argc,char *argv[]) {
char *userInput[10];
time_t t;
int num = atoi(argv[1]);
srand(time(NULL));
for (int i = 0; i <= num; i++) {
printf("%d\n", rand() % MAXNUM);
}
return 0;
}
the problem is that it generates new random numbers. But I want to use the output of this program and multiply it with 2 with program 2
I think I fixed it! Yeehawww!
It was the srand() causing this problem. Uncommenting that solved it.
How to redirect more than one text file in c program? For example I have the following C code:
//redirection.c
#include<stdio.h>
main()
{
int x,y;
scanf("%d",&x);
x=x*x;
printf("%d",x);
scanf("%d",&y);
y=x+y;
printf("%d",y);
}
After compiling this code I created two text files text1.txt having the value 8 and text2.txt having the value 6.
When I give input to this program using command line redirection (as redirection<text1.txt), it gives output 64 and does not wait to take another input (and program exits) which I want to give another input from text2.txt.
Is there any solution how can I send another input via text2.txt for second scanf function in the above program?
While giving the input as redirection as like this.
cat a b | ./a.out.
Or else you can use the command line arguments.
#include<stdio.h>
main(int argc, char *argv[])
{
FILE *fp, *fp1;
if ( (fp=fopen(argv[1],"r")) == NULL ){
printf("file cannot be opened\n");
return 1;
}
if (( fp1=fopen(argv[2],"r")) == NULL ){
printf("file cannot be opened\n");
return 1;
}
int x,y;
fscanf(fp,"%d",&x);// If you having only the value in that file
x=x*x;
printf("%d\n",x);
fscanf(fp1,"%d",&y);// If you having only the value in that file
y=x+y;
printf("%d\n",y);
}
you can also use command line arguments:
#include <stdio.h>
#define BUFSIZE 1000
int main(int argc, char *argv[])
{
FILE *fp1 = NULL, *fp2 = NULL;
char buff1[BUFSIZE], buff2[BUFSIZE];
fp1 = fopen(argv[1], "r");
while (fgets(buff1, BUFSIZE - 1, fp1) != NULL)
{
printf("%s\n", buff1);
}
fclose(fp1);
fp2 = fopen(argv[2], "r");
while (fgets(buff2, BUFSIZE - 1, fp2) != NULL)
{
printf("%s\n", buff2);
}
fclose(fp2);
}
here is a more cleaned up version:
#include <stdio.h>
#define BUFSIZE 1000
void print_content(char *file);
int main(int argc, char *argv[])
{
print_content(argv[1]);
print_content(argv[2]);
}
void print_content(char *file){
char buff[BUFSIZE];
FILE *fp = fopen(file, "r");
while (fgets(buff, sizeof(buff), fp) != NULL)
{
printf("%s\n", buff);
}
fclose(fp);
}
I have a C code to read a txt file:
#include <stdio.h>
int main()
{
FILE *pf;
int ii;
int jj;
char *filename;
printf("enter file name");
scanf("%s",filename);
printf("%s",filename);
pf = fopen("filename+.txt", "r");
if(pf==Null)
{
printf("cant open");
}
else
{
fscanf(pf,"%d,%d" ,&ii,&jj );
printf("%d,%d\n" ,ii,jj);
}
fclose(pf);
return 0;
}
Still i get segmentation error.
The input txt file contains
2,3
I get segmentation fault(core dumped) when i run the program as ./readfile input.
What is going wrong here , how can i correct this?
int main(char *) is not a legal signature for main in C. Only
int main(void)
and
int main(int argc, char **argv)
are legal. In your case, you will need the latter.
That is not the correct way to specify arguments to your program. ie you can't do this:
int main(char *filename)
There should have been a compiler error when you compiled your program. The correct definition is:
int main( int argc, char **argv )
Where argv is an array of strings. Try doing this experiment:
int main( int argc, char **argv )
{
int i;
for( i = 0; i < argc; i++ ) {
printf( "arg %d is: \"%s\"\n", argv[i] );
}
return 0;
}
Then, write your program to use the correct argument list as above.
One other point to make is that you should test the return value of fopen. If it is NULL, then you should NOT try to access the file (because it failed to open).
There are many mistakes here.
After calling fopen(), you should check if pf is NULL, because fopen() can fail.
You are trying to open the file of name filename+.txt. Shouldn't you be opening the file which the name was provided as parameter?
Also, the structure of main() should be int main(int argc, char **argv), you cannot do whatever you want about this.
Check if argc > 1, in which case the program was started with parameters, and the file name should've been provided in argv[1].
Update on comments: This is how your code should look like:
int main()
{
char filename[512]; // reserve 512 bytes to receive the file name from input
FILE *pf;
int ii;
int jj;
printf("Enter file name: ");
scanf("%s", filename);
pf = fopen(filename, "r");
if (pf)
{
fscanf(pf,"%d,%d", &ii, &jj);
printf("%d,%d\n", ii, jj);
fclose(pf);
}
else
{
printf("Failed to open file name %s", filename);
}
return 0;
}
You can also do this to get the filename from the parameters:
int main(int argc, char **argv)
{
FILE *pf;
int ii;
int jj;
if (argc > 1)
{
pf = fopen(argv[1], "r");
if (pf)
{
fscanf(pf, "%d,%d", &ii, &jj);
printf("%d,%d\n", ii, jj);
fclose(pf);
}
else
{
printf("Failed to open file name %s", argv[1]);
}
}
else
{
printf("Insuficient parameters");
}
return 0;
}
Or even, if you don't want to pass the file extension:
int main(int argc, char **argv)
{
char *filename;
FILE *pf;
int ii;
int jj;
if (argc > 1)
{
filename = malloc(strlen(argv[1]) + 5); // alloc necessary memory
strcpy(filename, argv[1]);
strcat(filename, ".txt");
pf = fopen(filename, "r");
if (pf)
{
fscanf(pf, "%d,%d", &ii, &jj);
printf("%d,%d\n", ii, jj);
fclose(pf);
}
else
{
printf("Failed to open file name %s", filename);
}
}
else
{
printf("Insuficient parameters");
}
return 0;
}