Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 8 years ago.
Improve this question
Compilable Code
`
#include <stdio.h>
#include <stdlib.h>
FILE * openFile(int argc, char *argv[]);
int readMonth(FILE *fin);
int main(int argc, char *argv[])
{
int month, choice;
int * temps;
FILE * fin = NULL;
fin = openFile(argc, argv);
month = readMonth(fin);
}
FILE * openFile(int argc, char *argv[])
{
int test;
FILE * fin = NULL;
fin = fopen(argv[2], "r");
fscanf(fin, "%d", &test);
if(fin==NULL){
perror("fopen");
exit(1);}
return fin;
}
int readMonth(FILE *fin)
{
int month=0;
int n = fscanf(fin, "%d", &month);
if(n!=1)
{printf("error reading month from file\n");
exit(1);}
printf("%d\n", month);
return month;
}`
I am trying to read data out of a text file and I'm getting weird results.
I call fileOpen from main to return the file pointer, this is my function:
FILE * fileOpen(int argc, char *argv[])
{
FILE* fin = NULL;
fin = fopen(*argv, argc);
return fin;
}
then calling readMonth to read the first line of the file, it does not print the correct
int.
int readMonth(FILE *fin)
{
int month=0;
fscanf(fin, "%d", &month);
printf("%d", month);
return month;
}
I am not sure if the error is with the file opening or the reading the file.
Here are some suggestions. 1. Check the return value of fopen
FILE *fileOpen(int argc, char *argv[] {
FILE* fin = NULL;
fin = fopen(*argv, "r");
if(fin == NULL) { // this block is new
perror("fopen");
exit(1);
}
return fin;
}
Note: If the argc and argv are from main, then *argv is argv[0] which is the name of the program. You probably want argv[1]. And you should check that argc >= 2 in main.
2: Check the return value of fscanf:
int readMonth(FILE *fin)
{
int month=0;
int n = fscanf(fin, "%d", &month);
if(n != 1) { // this block is new
printf("error reading month from file\n");
exit(1);
}
printf("%d", month);
return month;
}
With these two changes your code should function properly.
You can read the first line of the file using fgets in function readmonth
char buffer[1024];
char *l ;
if((l=fgets(buffer,sizeof(buffer),fin))!=NULL)
printf("%d",atoi(l));
Also , you can check if the file opening failed using
if(fin == NULL)
printf("failed");
FILE * file = fopen(data, "r");
if(file==NULL){
printf("404 File Not Found\n");
exit(-1);
}
while(1)
{
char line[100];
int res = fscanf(file, "%s", line);
if(res == EOF)
break;
fscanf(file, "%s", &var);
// handle the var
}
Related
I'm reading file using fread().[read file only]
On compilation, the compiler throws a "Segmentation fault (core dumped)" error.
I'm using structure.
I wrote this code.
type #include <string.h>
#include <stdio.h>
#include <stdlib.h>
int twilio_send_functionapi(char *channel, char *status); // function declartion
struct credentials
{
char *account_sid;
char *auth_token;
char *from_number;
char *to_number;
} c1;
int main(int argc, char *argv[])
{
FILE *fp;
struct credentials input;
fp = fopen("data.config", "r");
if (fp == NULL)
{
printf("Error\n");
return -1;
}
dentials.to_number = (char*)malloc(sizeof(char)*100);
while(fread(&c1,sizeof(struct credentials),1 ,fp))
fscanf(fp,"%s %s %s %s", c1.account_sid, c1.auth_token,c1.from_number, c1.to_number);
char *channel,*status;
channel = argv[1];
status = argv[2];
twilio_send_functionapi(channel,status); //function call
}
Don't know where I'm mistaken.
here is .conf file which needs to be read
account_sid : AC40cfb4f3e98b55b13a9b93527683171e
auth_token : 5f6906d7847ad1fc1fc1170ab60e40fd
from_number : 15867854760
to_number : 1212321123
Instead of fread(), fscanf(), use fgets() to read a line of the file into a string.
// 123456789 123456789 123456789 123456789
//account_sid : AC40cfb4f3e98b55b13a9b93527683171e
#define SID_LEN 34
struct credentials {
char account_sid[SID_LEN + 1]; // Use array here, not pointer.
// ... omitted for brevity
} c1;
#define LINE_SIZE 100
char line[LINE_SIZE];
if (fgets(line, sizeof line, fp)) {
if (sscanf(line, "account_sid : %34s", c1.account_sid) == 1) {
; // Success
} else {
; // Failed
}
Continue likewise for the other c1 members`.
Thank you everyone.
I resolve my problem.
char credential[4][100] ;
int main()
{
FILE *fp;
fp = fopen("data.config", "r");
if (fp == NULL)
{
printf("Error\n");
return -1;
}
printf("File is opened\n");
if ((fscanf(fp,"account_sid-%s\n",credential[0])!= 1))
{
printf("error reading account_sid value\n");
return -1;
}
fclose(fp);
}
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 want to open a file using the arguments when executing it, for example:
./Project 123.txt
I can make this work to some extent, but if I try to pass the arguments into a function, and then call the function, something is not working quite right.
Here is the function I have, which will read the lines from a text file:
int numeroLinhas(){
int ch;
FILE *fp;
int linhas=0;
fp = fopen("123.txt","r");
while( ( ch = fgetc(fp) ) != EOF ){
if(ch=='\n'){
linhas++;
}
}
fclose(fp);
fprintf(stats, "linhas: %d\n", linhas);
}
int main(int argc, char *argv[]){
FILE *fp;
fp = fopen(argv[1],"r");
numeroLinhas();
}
So, I would like to know how can I pass the argv[] has an argument into my numeroLinhas() function, so that I don't have to call the name of the file at all during the coding, just when executing.
The problem is that you have hard-coded the file name to open. Modify your function to take an argument, a string naming the file.
Then just pass the correct argv entry as the argument to the function, after checking the number of arguments to the program first.
Pass the name of the file to the function that counts the lines in the file:
#include <stdio.h>
void numeroLinhas(const char *filename)
{
int ch;
int linhas = 0;
FILE *fp = fopen(filename, "r");
if (fp == 0)
{
fprintf(stderr, "Failed to open file %s for reading\n", filename);
return;
}
while ((ch = fgetc(fp)) != EOF)
{
if (ch == '\n')
linhas++;
}
fclose(fp);
fprintf(stats, "linhas: %d no %s\n", linhas, filename);
}
int main (int argc, char *argv[])
{
for (int i = 1; i < argc; i++)
numeroLinhas(argv[i]);
return 0;
}
Error check fopen() calls; they fail. Handle the int returned by fgetc() correctly. Change the function to return void since there isn't a return. Report errors on standard error. Include file name in the outputs (error and routine). Invoke the function on all arguments provided. Don't say anything if no arguments are provided — or add if (argc < 2) { fprintf(stderr, "Usage: %s file [...]\n", argv[0]); return 1; } before the loop in main().
Sorry about mixed English/Portugese messages.
int numeroLinhas(char *filename){
char ch;
FILE *fp;
int linhas=0;
fp = fopen(filename,"r");
while( ( ch = fgetc(fp) ) != EOF ){
if(ch=='\n'){
linhas++;
}
}
fclose(fp);
fprintf(stats, "linhas: %d\n", linhas);
}
int main (int argc, char *argv[]){
//should have an if for argc size
char *filename = argv[1];
numeroLinhas(filename);
}
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;
}