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;
}
Related
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;
}
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 wanted to learn how to use getc function in C so I wrote a little program that is supposed to give the first letter of a text file as an output.
Here's how it looks:
int main()
{
int character;
FILE *file;
file = fopen("file.txt", "r");
if(file == NULL)
printf("can't open\n");
character = getc(file);
printf("%c", character);
fclose(file);
return 0;
}
It fails to open the file.txt file and I can't figure out why. file.txt is in the same folder as my program's .exe file. I'm using Windows Vista.
Thanks in advance
This extracts the program's location from argv[0]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MYFILE "plik.txt"
int main(int argc, char *argv[]) {
char fname[_MAX_PATH+1];
int znak;
FILE *plik;
char *ptr;
strcpy(fname, argv[0]);
ptr = strrchr(fname, '\\');
if(ptr == NULL) {
strcpy(fname, MYFILE);
}
else {
strcpy(ptr+1, MYFILE);
}
plik = fopen(fname, "r");
if(plik == NULL) {
printf("Can't open %s\n", fname);
}
else {
znak = getc(plik);
printf("First char of %s is %c\n", fname, znak);
fclose(plik);
}
getchar();
return 0;
}
Try
if (plik == NULL) { perror("plik.txt"); exit(EXIT_FAILURE); }
for a better understanding of the cause of error.
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 wrote this code to read a variable in a .txt file, ignore the first character and convert into a integer.It works but looks dumb, is there a better way to do this? I'm using just one string here but it's supposed to work with four.
void read(char a[])
{
int i;
char a1[3];
for (i = 0; i<3; ++i){
a1[i]= a[i+1];
}
int b1 = atoi(a1);
}
int main()
{
FILE *file;
file = fopen( "file.txt", "r");
if (file == NULL) {
printf( "Arquivo nao encontrado\n");
}
char a[4];
fscanf(file, "%s\n",&a);
read(a);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char filename[] = "file.txt";
FILE *fp = fopen(filename, "r");
if (fp == 0)
{
fprintf(stderr, "Failed to open file %s for reading\n", filename);
return(EXIT_FAILURE);
}
int value;
if (fscanf(fp, "%*c%d", &value) != 1)
{
fprintf(stderr, "Failed to read integer value from file %s\n", filename);
fclose(fp);
return EXIT_FAILURE;
}
printf("Read %d\n", value);
fclose(fp);
return 0;
}
The %*c reads a single character but does not assign it. The * to suppress an assignment is a general mechanism in the scanf()
family of functions.
Untested code.