How can I read integer from file with cmd in c - c

This is input.txt
5343
232
5
int main(int argc, char *argv[]) {
int x;
int sum=0;
int count=0;
if(argc==1)
printf("Error message!");
if(argc>=2)
{
FILE* file = fopen (argv[1], "r");
while(!feof(file)){
fscanf(file,"%d",&x);
sum+=x;
count++;
}
printf("%d", sum);
printf("%d", count);
return 0;
}
I use this main and write this in cmd=
c_file.exe input.txt
After that statement in cmd, there is no output and I can't write anything in cmd.
input.txt is given above I want to read and store the integer digit by digit how can I do it?

while(fscanf(file,"%d",&x) == 1)
{
sum+=x;
count++;
}

Related

windows reuse output from previous program as input in other program cmd redirect shell

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.

Reading numbers into array and printing off in reverse in C

I'm trying to open a file using command line arguments and read the numbers I have in my 'testdata' file in reverse The numbers in the test data file consist of:
2
20
200
2000
20000
-2
-20
-200
-20000.
Here is the code I have written so far. The file prints out, obviously not in reverse. I'm assuming I'm just missing a for loop in here somewhere. I'm also considering that maybe I should be using fscanf instead of fgets. Any input is appreciated.
#include <stdio.h>
#define MAX_NUMS 1000
int main(int argc, char *argv[]) {
Int a, n;
char buf[MAX_NUMS];
Int array[MAX_NUMS];
file *pt;
if (argc < 2) {
printf("Usage %s <files..>\n");
}
if ((pt = fopen(argv[1], "r")) == NULL) {
printf("Unable to open %s for reading.\n", argv[1]);
Return 1;
}
while (fgets(buf, MAX_NUMS, pt) != NULL){
printf("%s", buf);
}
for(j = 0; j < MAX_NUMS; j++){
If(fscanf(pt, "%d", &array[a]) != 1);
Break;
For(a = n; a--> 0;){
Printf("%d", array[a]);
}
fclose(pt);
retuern 0;
}
Use while(fscanf("%d", &n)){ a[i++] = n; } initiate i with 0 before and declare a as an integer array. Later while printing, printing it in reverse order. It is not possible to read from reverse order, though you can go to the end of the file using fseek().
There are some problems in your code:
the stream type is spelled FILE.
you do not return from the main() function in case of errors. The program keeps going and you have undefined behavior.
there is a missing argument in the first printf().
there is a typo on the return statement.
You could define the maximum number of numbers to handle, define an array for the numbers and use a loop index to store the numbers and later print them in reverse order.
Here is an example:
#include <stdio.h>
#define MAX_NUMBERS 1000
int main(int argc, char *argv[]) {
int array[MAX_NUMBERS];
int i, n;
FILE *pt;
if (argc < 2) {
printf("Usage %s <files..>\n", argv[0]);
return 1;
}
if ((pt = fopen(argv[1], "r")) == NULL) {
printf("Unable to open %s for reading.\n", argv[1]);
return 1;
}
for (n = 0; n < MAX_NUMBERS; n++) {
if (fscanf(pt, "%d", &array[n]) != 1)
break;
}
for (i = n; i-- > 0;) {
printf("%d\n", array[i]);
}
fclose(pt);
return 0;
}

Putting txt File Into Array is Starting at 12th Element

I'm writing a program in C, in which I am reading the data from a .txt file, and my goal is to put each element from the .txt file into an array. When I compile and run the program, the values of 50, 55, and 0 are returned. These are the ASCII values (I'm not sure why the elements are being stored as ASCII codes, but that's okay for now) for 2, 7, and 0 (meaning nothing was initialized since we reached the end of the .txt file. Why is my program not reading the .txt file from the beginning??
...
int main(int argc, char *argv[]){
FILE *inputFile;
char *input = argv[1];
char magicSquareArray[257];
inputFile = fopen(input, "r");
if (inputFile == 0){
printf("Cannot open file for reading!\n");
return -1;
}
fscanf(inputFile, "%s", magicSquareArray);
while (!feof(inputFile)){
fscanf(inputFile, "%s", magicSquareArray);
}
printf("%i\n", magicSquareArray[0]);
int sideSize = magicSquareArray[0];
int squareSize = sideSize * sideSize;
printf("%i\n", squareSize);
fclose(inputFile);
The text file:
3
4,3,8
9,5,1
2,7,6
Perhaps you want the code such as the following.
(However, I think in the following manner.
To prepare an array read the first number,
To assign a numerical value to read into it.)
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
FILE *inputFile;
char *input = argv[1];
char magicSquareArray[257];
int ch, len;
inputFile = fopen(input, "r");
if (inputFile == 0){
printf("Cannot open file for reading!\n");
return -1;
}
len = 0;
while((ch = fgetc(inputFile)) != EOF && len < sizeof(magicSquareArray)-1){
magicSquareArray[len++] = ch;
}
magicSquareArray[len] = 0;
fclose(inputFile);
printf("%c\n", magicSquareArray[0]);
int sideSize = atoi(magicSquareArray);
int squareSize = sideSize * sideSize;
printf("%i\n", squareSize);
return 0;
}

How to redirect more than one text file in c programm

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);
}

To read the content of a file in C

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;
}

Resources