Reputation: 1
I'm trying to write a program that will read the first line of a txt file and output it. I can't get the fgets to display in my fprintf statement when running the program.
#include "example.h"
// function: main
int main(int argc, const char** argv) {
//declare filepointer
FILE *fp;
//declare variables
char c[10];
long size;
//open file
fp = fopen(argv[1], "r");
//first output read dimension of vector
fgets (c, 10, fp);
fprintf(stdout, "the dimension of the vector is %s\n", c);
fclose(fp);
return 0;
}
The text file has the following contents:
4
45.0
62.0
55.6
8.2
But my output is just reading as: the dimension of the vector is
Upvotes: 0
Views: 666
Reputation: 7726
You always need to be careful of what the user is going to enter as input in the program. To do this, as mentioned in the comment, we should always check if the fopen()
, fgets()
, and the arguments are correctly passed before taking them into use.
Let's try the following code:
#include <stdio.h>
#define EXIT_FAILURE 1
#define MAX_LEN 16
int main(int argc, char *argv[]) {
FILE *fp = NULL;
char c[MAX_LEN];
if (argc != 2) {
fprintf(stdout, "Usage: %s <file>\n", argv[0]);
return EXIT_FAILURE;
}
fp = fopen(argv[1], "r");
if (fp == NULL) {
perror(argv[1]);
fclose(fp); // Cleanup
return EXIT_FAILURE;
}
if (fgets(c, sizeof(c), fp) == NULL) {
fprintf(stderr, "File read error.\n");
fclose(fp); // Cleanup
return EXIT_FAILURE;
}
fclose(fp);
fprintf(stdout, "The dimension of the vector is %s\n", c);
return 0;
}
In this case, I've got those same values as yours in the data.txt
file.
The program outputs:
rohanbari@genesis:~/stack$ ./a.out data.txt
The dimension of the vector is 4
Upvotes: 2