I'm a student learning C for the first time. I typed in an example the professor gave the class, which is supposed to read in some integers from a file called "input.txt".
Here's the code:
#include <stdio.h>
int main() {
FILE *ifp;
int num = -1, sum = 0;
ifp = fopen("input.txt", "r");
while (num!= 0) {
fscanf(ifp, "%d", &num);
sum +=num;
}
fclose(ifp);
printf("The sum is %d.\n", sum);
return 0;
}
I'm trying to get this program to print out the "sum" like it should, but when I run it, there are no errors yet the only output I get is (11db).
I created a file called "input.txt" and saved it to the desktop, but it's not working.
The file "input.txt" contains:
1
2
3
4
5
I don't know if I'm supposed to somehow, somewhere, define the file path or where/how to do this.
Any help is much appreciated.
Thanks!
My guess would be that the error is because opening the file fails. You should check that fopen returns non-NULL. Opening a file is an operation that often fails. For example:
ifp = fopen("input.txt", "r");
if (ifp == NULL) {
fprintf(stderr, "Couldn't open the file for reading.\n");
}
Unless given a full path name starting with a "/", fopen opens files in the current working directory of the process, and that is probably not the desktop.
Also, when you reach the end of the file, fscanf will return the value EOF. The variable num will not be set to zero. This is a way to read a file of integers:
while (fscanf(ifp, "%d", &num) == 1) {
sum += num;
}
Related
I am trying to write a simple C program which will read data from a csv file and perform some calculations on this data.
Unfortunately I have a problem where a file pointer of mine, fptr , is not being assigned a value after calling fopen(). I know this is the case after stepping through VS 2017's debugger. Yet I do not know why this is the case. This is a huge problem and means my program will throw some very nasty exceptions any time I try to read data from the file or close the file.
My code is below:
main.c
#include<stdio.h>
#include <stdlib.h> // For exit() function
#include"constants.h" //For access to all project constants
/***************************************************************************************************************
To keep the terminal from automatically closing
Only useful for debugging/testing purposes
***************************************************************************************************************/
void preventTerminalClosure() {
//flushes the standard input
//(clears the input buffer)
while ((getchar()) != '\n');
printf("\n\nPress the ENTER key to close the terminal...\n");
getchar();
}
/***************************************************************************************************************
Read the given input file
***************************************************************************************************************/
void readInputFile(char fileName[]) {
FILE *fptr;
char output[255];
//open the file
if (fptr = fopen(fileName, "r") != NULL) { //read file if file exists
//fscanf(fptr, "%[^\n]", output);
//printf("Data from the file:\n%s", output);
printf("<--Here-->");
}else {
printf("\nERROR 1: File %s not found\n", fileName);
preventTerminalClosure();
exit(1);
}
fclose(fptr); //close the file
}
/***************************************************************************************************************
* * * Main * * *
***************************************************************************************************************/
void main() {
char testName[MAX_NAME_SIZE];
printf("Hello World!\n");
printf("Please enter your name: ");
scanf("%s", testName);
printf("It's nice to meet you %s!", testName);
readInputFile("dummy.txt");
preventTerminalClosure(); //Debug only
}
I have made sure that my fake file does indeed exist and is located in the correct location. Otherwise my code would hit the else block inside of readInputFile(). That is something I have thoroughly tested.
There is clearly something basic that I am missing which explains this pointer behavior; but what that is, I am not sure. Any help would be appreciated! :)
Use parenthesis to enforce order, so that fptr is compared against NULL after it has been assigned value returned by fopen:
FILE *fptr;
char output[255];
//open the file
if ( (fptr = fopen(fileName, "r")) != NULL)
I made file that I want to update with the value when the program ends, then read the value from that file again next time the program runs.
For example: In this program I want to subtract an entered value from the saved one. So first I enter 3 then it gives 12. When I run the program again and enter 2, then it gives 13, but it should give 10 rather than 13.
#include<stdio.h>
#define PATH "/tmp/file"
int main()
{
FILE *file;
int age=15,s;
scanf("%d",&s);
file = fopen(PATH, "w");
age = age - s;
fprintf(file, "%d", age);
fclose(file);
file = fopen(PATH,"r");
if (file == NULL)
{
printf("files does not exist");
}
fscanf(file,"%d",&age);
printf("%d",age);
fclose(file);
}
The problem is that you always initialize age to 15, not to what's in your file. Then you write that age to the file, and immediately read it back.
If I understand you correctly, you want to read the file first (not overwrite it), then do your calculation, and write the result back.
#include<stdio.h>
#define PATH "/tmp/file"
int main()
{
FILE *file;
int age = 15, s;
file = fopen(PATH, "r");
if (file == NULL)
{
printf("files does not exist");
return 1;
}
fscanf(file, "%d", &age);
fclose(file);
scanf("%d", &s);
file = fopen(PATH, "w");
age = age - s;
fprintf(file, "%d", age);
fclose(file);
printf("%d", age);
}
Note that you should also do error handling for writing, not only for reading. Writing can fail if the file system is full, or if you don't have write permissions.
Your error handling isn't complete, though: in your code you print an error message, but still keep going. Accessing an invalid file pointer (i.e., NULL) will crash your program with a segmentation fault. I've added a return statement, but you could also put the rest of the logic in an else block.
I have the following code:
#include <stdio.h>
#include <stdlib.h>
int main() {
long num = 0;
FILE *fptr;
if ((fptr = fopen("test_num.txt","r+")) == NULL){
printf("Error! opening file");
return -1;
}
fscanf(fptr,"%ld", &num);
// Increment counter by 1
num += 1;
printf("%ld\n", num);
fprintf(fptr, "%ld", num);
fclose(fptr);
return -1;
}
With the aforementioned code I am trying to read the content of the file, which always has a long value stored and nothing else, increment the value by 1 and then overwrite the lond value of the file with the new incremented value. However, I am trying to do this without closing and file in between reading/writing. Fo example, the workflow/algorithm should be as follows:
Step 1: Open the file
Step 2: Read the long value from the file
Step 3: Increment the long value by 1
Step 4: Overwrite the long value of the file by new incremented value
Step 5: Close the file
However, if I use the aforementioned code then the output value appends the incremented value at the end of the file instead of overwriting. I have tried opening the file with "w+" and "w" but of course these only work for writing but not reading the file as mentioned above. Can anyone know what I can do to achieve the goal?
The answer happens to be: I needed to rewind the file ponter back to the index 0 of the file in order to overwrite the content of the file with the incremented value. The correct code is as follows:
#include <stdio.h>
#include <stdlib.h>
int main() {
long num = 0;
FILE *fptr;
if ((fptr = fopen("test_num.txt","r+")) == NULL){
printf("Error! opening file");
return -1;
}
fscanf(fptr,"%ld", &num);
// Increment counter by 1
num += 1;
printf("%ld\n", num);
rewind(fptr); // Rewind to index 0 of the fptr
fprintf(fptr, "%ld", num);
fclose(fptr);
return -1;
}
There are two common ways to rewrite parts of a text-file:
Read the while file into memory, make the change, and write it back out from the beginning.
Read parts of the file (for example line by line), making the change on the fly, and writing to a new temporary file. Then rename the temporary file as the actual file.
Im trying to write to files using fopen, with a NULL check in case there is an error opening the file or it does not exist. However despite the file not existing the pointer returns with an arbitrary number instead of being NULL. Why is this happening and how can I correct it?
My code is below:
#include<stdio.h>
#include<stdlib.h>
int writenumstofile(int num1, int num2)
{
FILE* fp;
if ((fp = fopen("outpiuteuo.txt", "w")) == NULL) {
return 7;
exit(1);
}
fprintf(fp, "%d", num1);
fprintf(fp, "%d", num2);
return 0;
}
It is creating a file if it doesn't exist. If you don't want the file to be created then use r+ file or simply first open the file in r mode and the proceed with w mode.
I recently done a program and ended up getting wrong on my homework. I had all the right steps however, I was not supposed to do it from the command line but run it from the IDE (if that makes sense).
What I am supposed to do is go into the file "numbers.txt" and read the integers in it (there are numbers already in there). I am suppose to find the sum, product and the highest integer and output those to a text called "stat.txt". However, I am confused on how to do it from my compiler. I have both files in the same directory however when I run it in the compiler, it says "Can not read input file." and I have no idea how to use the compiler to just read the text files because I am so use to using the command line.
Here's my code (I could not get max to fit in with the code).
int main (int argc, char *argv[]) {
int number = 0;
int sum = 0;
int product = 1;
int max = 0;
FILE *input, *output;
input = fopen("numbers.txt", "r");
output = fopen("stat.txt", "w");
if (input == NULL) {
printf("Can not read the input file\n");
exit(-1);
}
while ((fscanf(input, "%d", &number)) != EOF) {
sum = sum + number;
product = product * number;
if (number > max){
max = number;
}
}
fprintf(output, "Sum : %d\n", sum);
fprintf(output,"Product : %d\n", product);
fprintf(output, "Largest: %d", max);
fclose(input); fclose(output);
}
What IDE are you using? You are supplying fopen with a relative path to numbers.txt, it must exist in the same directory as the executable.
Either place numbers.txt into the same folder where your IDE builds the program, or supply it with an absolute path like '/home/username/Desktop/number.txt'