I am trying to read a file in C. First I am calculating the lines in the file:
int main(int argc, char* argv[])
{
if (argc < 2)
{
printf("No file specified");
exit(1);
}
FILE* pFile;
char currentCharacter;
int lines = 1;
pFile = fopen(argv[1], "r");
for (currentCharacter = getc(pFile); currentCharacter != EOF; currentCharacter = getc(pFile))
{
if (currentCharacter == '\n') lines++;
}
...
}
After calculating the lines in the file, I tried reading one by one, like this:
char currentLine[255];
for (int i = 1; i <= lines; i++)
{
fgets(currentLine, 255, pFile);
printf("%s\n", currentLine);
}
fclose(pFile);
But everytime I run it, I am getting this output:
²a
When I try to remove the for loop and place fgets() and printf() outside, it prints NOTHING
If you are wondering, here is the content of the file I am trying to read:
test.txt
test1
test2
test3
NOTE: The file is being successfully opened as it is counting the lines correctly.
As said in the comments, no need to count the lines. Just stop when there is nothing more to read. That is, when fgets returns NULL.
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char* argv[])
{
if (argc < 2)
{
printf("No file specified");
exit(1);
}
FILE* pFile = fopen(argv[1], "r");
if(pFile==NULL)
{
printf("File is not found");
exit(1);
}
char currentLine[256];
while(fgets(currentLine, 256, pFile))
{
printf("%s", currentLine);
}
return 0;
}
Related
This question already has answers here:
Read from file or stdin
(6 answers)
Closed 2 years ago.
I have a program that calculates a lottery tickets (this tickets are in a file.txt), and writes the winners tickets in another file. I have a subfunction called evaluate_tickets(file, lottery_numers, winner....)
In shell I write: ./program arg1 arg2... (arg1, arg2 are text files i.e. file.txt)
But now, I want to do ./program < file.txt. The problem is that I don't know how to send the parameter "file" of evaluate_tickets because I receive information by stdin.
Define a stream pointer FILE *fp; to read to input file:
If you want the input to be read from a file, use fp = fopen(filename, "r"); to open the file and close the stream after processing with fclose(fp);.
If you want the input to be read from standard input, just assign fp = stdin; instead of using fopen().
Here is a short example:
#include <stdio.h>
int main(int argc, char *argv[]) {
FILE *fp;
int c, lines;
if (argc > 1) {
fp = fopen(argv[1], "r");
if (fp == NULL) {
fprintf(stderr, "cannot open %s\n", argv[1]);
return 1;
}
} else {
fp = stdin; /* read from standard input if no argument on the command line */
}
lines = 0;
while ((c = getc(fp)) != EOF) {
lines += (c == '\n');
}
printf("%d lines\n", lines);
if (argc > 1) {
fclose(fp);
}
return 0;
}
Here is the same example with a cleaner approach, passing stdin or an open FILE pointer to an ad hoc function. Note how it handles all command line arguments:
#include <stdio.h>
void count_lines(FILE *fp, const char *name) {
int c, lines = 0;
while ((c = getc(fp)) != EOF) {
lines += (c == '\n');
}
printf("%s: %d lines\n", name, lines);
}
int main(int argc, char *argv[]) {
FILE *fp;
if (argc > 1) {
for (int i = 1; i < argc; i++) {
fp = fopen(argv[i], "r");
if (fp == NULL) {
fprintf(stderr, "cannot open %s\n", argv[i]);
return 1;
}
count_lines(fp, argv[i]);
fclose(fp);
}
} else {
/* read from standard input if no argument on the command line */
count_lines(stdin, "<stdin>");
}
return 0;
}
I am trying to figure out why this is not printing, I am trying to print each letter from a text file that is inputted through command prompt, but I am just getting an empty output... What am I doing wrong, and why does this not work? I feel like this logically should work. Thanks.
int main(int argc, char *argv[]) {
FILE *fp;
int i;
for (i = 1; i < argc; i++) {
printf("%s\n", argv[i]);
fp = fopen(argv[i], "r");
while (!feof(fp)) {
puts(fp);
}
fclose(fp);
}
return 0;
}
You are attempting to print a file pointer:
puts(fp);
Read the manual of puts() -that's not what it takes.
To read char-by-char and print on the stdout, you can do:
int ch;
fp = fopen(argv[i], "r");
if (!fp) {
perror("fopen");
exit(1);
}
while((ch=fgetc(fp)) != EOF) {
putchar(ch);
}
flcose(fp);
Unless you are passing multiple file names as arguments, your outer loop doesn't make much sense.
Your program has multiple problems:
You do not test the return value of fopen(): the program invokes undefined behavior if any of the command line arguments cannot be opened as a stream for reading.
while(!feof(fp)) is incorrect. Read this: Why is “while ( !feof (file) )” always wrong?
puts(fp); is incorrect as fp is a FILE *, not a string. Use a loop to copy the file contents one byte at a time.
Here is a corrected version:
#include <errno.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
FILE *fp;
int i, c;
for (i = 1; i < argc; i++) {
fp = fopen(argv[i], "r");
if (fp == NULL) {
fprintf(stderr, "cannot open %s: %s\n", argv[i], strerror(errno));
} else {
printf("%s\n", argv[i]);
while ((c = getc(fp)) != EOF) {
putchar(c);
}
fclose(fp);
}
}
return 0;
}
int main(int argc, char *argv[]) {
FILE *fp;
int i;
char buff[128];
for (i = 1; i < argc; i++) {
printf("\n%s\n", argv[i]);
if(NULL == (fp = fopen(argv[i], "r"))){//check open file
perror("fopen");
continue;
}
while (fgets(buff, sizeof buff, fp)) {//read into buffer
fputs(buff, stdout);//print buffer (not add newline)
}
fclose(fp);
}
return 0;
}
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;
}
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);
}
I have to solve the following problem in C for the operating systems class:
At the command line three file are given, two for input, one for output.
The output file is obtained from input files, as follows: 10 bytes from
the first file, 20 bytes from the second file, next 10 bytes from the
first file, next 20 bytes from the second file and so on, until
an input file is finished.
Simple but inefficient solution: read and write groups of 10 / 20 bytes.
An efficient (but not simple) solution: read and write blocks
with 5000 bytes.
I tried this for the simple solution. But it doesn't work... Can anyone help me?
#include<stdio.h>
int main(int argc, char* argv[], char* envp[]){
if (argc != 4){
printf("%s", "Usage: c4h filename\n");
return 0;
}
int c1,c2,i;
FILE *in1;
FILE *in2;
FILE *out;
in1 = fopen(argv[1], "r");
in2 = fopen(argv[2], "r");
out = fopen(argw[3], "wb");
if (in1 == NULL){
printf("%s", "File not found!\n");
return 0;
}
if (in2 == NULL){
printf("%s", "File not found!\n");
return 0;
}
while(feof(in1)!=0 && feof(in2)!=0){
for(int i=0;i<20;i++)
if(feof(in1)!=0){
c1 = fgetc(in1);
fputc(c1,out);
}
for(int i=0;i<10;i++){
if(feof(in2)!=0){
c2 = fgetc(in2);
fputc(c2,out);
}
}
fclose(in1);
fclose(in2);
fclose(out);
return 0;
}
There were three problems with your code:
Typo with argw instead of argv
Missing closing } for the while loop
feof(file)!=0 evaluates to true when you are at the eof, the exact opposite of the condition you want, replace with !eof(file) which evaluates to true only if you are not at eof
And one smaller problem, you redefine the variable i in your for loops: for(int i=0;i<10;i++) should be for(i=0;i<10;i++) since you define i earlier in the code.
You should try compiling your code before taking it to SO! The code you posted didn't even compile for me. Here's the working code:
#include<stdio.h>
int main(int argc, char* argv[], char* envp[]){
if (argc != 4){
printf("%s", "Usage: c4h filename\n");
return 0;
}
int c1,c2,i;
FILE *in1;
FILE *in2;
FILE *out;
in1 = fopen(argv[1], "r");
in2 = fopen(argv[2], "r");
out = fopen(argv[3], "wb");
if (in1 == NULL){
printf("%s", "File not found!\n");
return 0;
}
if (in2 == NULL){
printf("%s", "File not found!\n");
return 0;
}
while(!feof(in1) && !feof(in2)){
for(i=0;i<20;i++)
if(!feof(in1)){
c1 = fgetc(in1);
fputc(c1,out);
}
for(i=0;i<10;i++){
if(!feof(in2)){
c2 = fgetc(in2);
fputc(c2,out);
}
}
}
fclose(in1);
fclose(in2);
fclose(out);
return 0;
};