i'm a begginer in programming and i have a task. I need to find the maximum number from file in.txt with content: 2,5,4,6,7,10 and then write it to file out.txt. Language C. The problems are:
I'm not very good in programing and in english(so if u will try to explane me something in english i don't think that i'll understand every word)
In the end there should be the max number on da screen, but it shows me the very first number
It's not my first theme here and every time the moderator give a link were i can read some text and find the answer, but look at priblem(1) there are too much text and i cannot tranlate everything in those answers(themes)
So help me please i'm a noob/ I have some code:
#include <conio.h>
#include <stdio.h>
main()
{
int N, max;
FILE *F;
F = fopen("in.txt", "r"); // open file
FILE *G;
G = fopen("out.txt", "w"); // open file
fscanf(F, "%d", &max);
while (feof(F))
{
fscanf(F, "%d", &N);
if (max < N)
max = N;
}
printf("max=%d", max); // show the result on the screen
fprintf(G, "%d", max); // put result into out.txt
fclose(F);
fclose(G);
}
Typo:
while(!feof(F))
^--- missing
feof returns TRUE if you're at the end of the specified file handle. Since you just started reading that file, you're NOT at the end, so feof() will return FALSE, and terminate your loop. You never actually read any further numbers.
Adding the ! makes it into "while NOT at the end of the file, read numbers".
Check to see if fopens succeed. Check if scanf succeed.
scanf will fail at EOF and drop out of loops
#include <stdio.h>
int main ()
{
int N,max;
FILE*F;
F=fopen("in.txt","r"); //open file
if ( F == NULL) { // check if fopen failed
printf ( "could not open in.txt\n");
return 1;
}
FILE*G;
G=fopen("out.txt","w"); //open file
if ( G == NULL) {
fclose ( F);
printf ( "could not open out.txt\n");
return 1;
}
if ( ( fscanf(F,"%d",&max)) == 1) // read an int into max. if success return is 1
{
while( ( fscanf(F,"%d",&N)) == 1) // read an int into N. if success return is 1
{
if(max<N)
{
max=N;
}
}
printf("max=%d",max);//show the result on the screen
fprintf(G,"%d",max); //put result into out.txt
}
fclose(F);
fclose(G);
return 0;
}
Related
I wrote this code where I generate random integers in a large quantity and store them in a txt file. it works if I input up to 49 integers
but after that it does not read any further from the file or the file don't accept any further I don't know please help me
this is the code
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fptr;
int num, n;
fptr = fopen("integers.txt", "w");
if (fptr != NULL)
{
printf("File created successfully!\n");
}
else
{
printf("Failed to create the file.\n");
return -1;
}
printf("Enter some integer numbers [Enter -1 to exit]: ");
scanf("%d", &n);
while (n != 0)
{
num = rand();
putw(num, fptr);
n--;
}
fclose(fptr);
fptr = fopen("integers.txt", "r");
printf("\nNumbers:\n");
int count = 0;
while ((num = getw(fptr)) != EOF)
{
printf("%d\n", num);
count++;
}
printf("\nNumber of elements in the file %d",count);
fclose(fptr);
return 0;
}
You have following problems:
As you're writing binary data, the file needs to be opened with "wb" and "rb" (b stands for binary). Othwerwise certain unwanted text substitutions will take place.
If one of your random numbers turns out to be -1, the read will stop prematurely because EOF has the value -1. Therefore you need to do the end of file check with the feof function instead of comparing the value read with EOF.
fptr = fopen("integers.txt", "wb"); // <<< open with binary mode "wb"
...
fptr = fopen("integers.txt", "rb"); // <<< open with binary mode "rb"
printf("\nNumbers:\n");
int count = 0;
while (1)
{
num = getw(fptr);
if (feof(fptr)) // end of file reached => stop the loop
break;
printf("%d\n", num);
count++;
}
BTW:
The documentation of getw concerning the return value is pretty misleading, especially the part "A return value of EOF indicates either an error or end of file" seems wrong to me. getw can read -1 values (0xffffffff) without problems.
#include <stdio.h>
main() {
int n;
FILE *file;
printf("We are here to create a file!\n");
file = fopen("demo.txt", "w+");
if (file != NULL)
printf("Succesfully opened!");
printf("Enter number\n");
while (scanf("%d", &n)) {
fprintf(file, "%d", n);
}
fclose(file);
}
why fscanf() is not working here? Here scanf is working properly but fscanf() is not responding or working here. Can anyone explain what the problem is?
Your code has some problems:
the prototype for main without arguments is int main(void)
you do not exit the program if the file cannot be opened. You will have undefined behavior if fopen returns NULL because you later pass this null pointer to fprintf.
the loop iterates until scanf() returns 0. You should instead iterate while scanf() returns 1. scanf() will return EOF if it fails at end of file, causing an infinite loop.
you should probably output a separator after the number in fprintf() otherwise all numbers are going to be clumped together forming a long sequence of digits.
main() should return 0 or an error status
Here is a corrected version:
#include <stdio.h>
int main(void) {
int n;
FILE *file;
printf("We are here to create a file\n");
file = fopen("demo.txt", "w");
if (file != NULL) {
printf("Successfully opened\n");
} else {
printf("Cannot open demo.txt\n");
return 1;
}
printf("Enter numbers\n");
while (scanf("%d", &n) == 1) {
fprintf(file, "%d\n", n);
}
fclose(file);
return 0;
}
Regarding your question: why can't I use fscanf() instead of scanf()?
you can use fscanf() as long as you give it a stream pointer opened for reading: if you write while (fscanf(stdin, "%d", &n) == 1) the program will behave the same way.
if you want fscanf() to read from file, you need to perform a file positioning command between read and write operations, such as rewind() of fseek(). Yet fscanf() will fail if there is no number to read at the current position in the file and since you open file with "w+" mode, fopen() will be truncated it.
You could cause an infinite loop by writing a number to the file, rewinding it to the beginning and re-reading the same number, etc.
Here is some code for illustration:
#include <stdio.h>
int main(void) {
int n;
FILE *file;
printf("We are here to create a file\n");
file = fopen("demo.txt", "w+");
if (file != NULL) {
printf("Successfully opened\n");
} else {
printf("Cannot open demo.txt\n");
return 1;
}
printf("Enter a number: ");
if (scanf("%d", &n) == 1) {
fprintf(file, "%d\n", n);
rewind(file);
while (fscanf(file, "%d", &n) == 1) {
printf("read %d from the file\n", n);
if (n == 0)
break;
rewind(file);
fprintf(file, "%d\n", n >> 1);
rewind(file);
}
}
fclose(file);
return 0;
}
Interaction:
We are here to create a file
Successfully opened
Enter a number: 10
read 10 from the file
read 5 from the file
read 2 from the file
read 1 from the file
read 0 from the file
I am trying to read values from a file and after some operation write to another file. Here facing a slight issue as I am also trying to save values in a 2D Array and displaying it. My file read and file write are showing correct results but my program throws an exception when it comes to display matrix part.
#include <stdio.h>
#include <ctype.h>
#ifndef NULL
#define NULL ((void *) 0)
#endif
int main(void)
{
FILE *file = NULL; //for file read
FILE *fptr = NULL; //for file write
int mat[182][274];
// code to read and display number from file
// open file for reading
file = fopen("file.txt", "r");
fptr = fopen("file1.txt", "w");
int i = 0,j=0;
fscanf (file, "%d", &i);
while (!feof (file))
{
symbol = fgetc(file);
if (symbol == '\n' || feof(file))
{
fprintf (fptr,"\n");
printf("\n");
}
else{
j=255-i;
mat[i][j]=j;
fprintf (fptr,"%d ", j);
fprintf (fptr," ");
printf ("%d ", j);
}
fscanf (file, "%d", &i);
}
fclose (file);
fclose (fptr);
//Facing issue in this part
int k;
int l;
for (k=0;k<=182;k++)
{
for(l=0;l<=274;l++)
{
printf("%d ", mat[k][l]);
}
}
return 0;
}
Arrays in C start at 0 and end at (array_size - 1).
As you're accessing memory just outside the array, you're most likely experiencing segmentation faults.
To fix this issue, change these lines:
for (k=0;k<182;k++)
{
for(l=0;l<274;l++)
{
printf("%d ", mat[k][l]);
}
}
Notice that I changed the relational operators from <= and >= to < and >, respectively.
Along with that, you may need to fully initialize your array. Odd values may be printed if the array is not initialized. (#Weather Vane).
However, to best be sure if this is the case, we need file.txt and file1.txt.
I am learning to program in C. Please explain why my program doesn't work. What is wrong? The program creates a file, writes a number into this file, and increases this number each time I run this program. The program counts how many times I have opened the file.
#include <stdio.h>
int main (void)
{
int n;
int c;
FILE* f = fopen("count_pr.bin", "a+");
if ((c=fgetc(f)) == EOF)
{
n=1;
fputc(n, f);
}
else
{
++n;
fseek(f, 0, SEEK_SET);
fputc(n, f);
}
printf ("The program was opened: %d\n", n);
fclose(f);
}
In the "a+" mode, from here
append/update: Open a file for update (both for input and output) with all output operations writing data at the end of the file. Repositioning operations (fseek, fsetpos, rewind) affects the next input operations, but output operations move the position back to the end of file. The file is created if it does not exist.
Output operations move the position back to the end of the file. So every write you do will be at the end of the file.
In addition, you need to make changes as suggested by Klas
If you want to overwrite the number each time, you should use r+ mode
read/update: Open a file for update (both for input and output). The file must exist.
There is still the issue of creating the file if it does not exist, so in that case, if the file cannot be opened in r+ mode, then you can open it in "w" or "w+" mode and only write to it.
I have updated the code below.
#include <stdio.h>
int main (void)
{
int n;
int c;
FILE* f = fopen("count_pr.bin", "r+");
if (f == NULL)
{
f = fopen("count_pr.bin", "w");
if (f != NULL)
{
n = 1;
fputc(n, f);
}
else
{
printf (" File Open Error");
exit(1);
}
}
else
{
c=fgetc(f);
n = c+1;
fseek(f, 0, SEEK_SET);
fputc(n, f);
}
printf ("The program was opened: %d\n", n);
fclose(f);
}
You read the value into c. Then you increase the uninitialized variable n by one and write n to the file. Since n is uninitialized you invoke undefined behaviour.
You need to use the value you read:
else
{
n = c + 1; // Changed line
fseek(f, 0, SEEK_SET);
fputc(n, f);
}
My program requires me to read a dat file with a list of numbers. My goal is to get each number and add them to an array. The file has around 100 numbers in this format:
1
2
3
(styling is a bit off sorry ;[ )
so far i have
int main()
{
double prices[1000];
int count,price;
FILE *file;
file = fopen("price.dat","r");
if(file == NULL)
{
printf("Error: can't open file to read\n");
}
else
{
printf("File prices.dat opened successfully to read\n");
}
if (file){
while (fscanf(file, "%d", &price)!= NULL){
count++;
prices[count]=price;
}
}
fclose(file);
}
Problem is that it continues adding the last number continuously. Any help?
You have several problems in your code. To name a few:
fscanf doesn't return a pointer so you shouldn't be comparing it with NULL. All scanf functions returns an integer which can be positive, zero or negative.
You don't initialize count so it will contain a seemingly random value.
Indexing of arrays starts a zero, so you should not increase the array index count until after the assignment.
The actual problem with not wanting to stop is because of the first point.
#include <stdio.h>
#include <string.h>
#define PRICES_LIST_MAX 1000
#define PRICES_FILE "price.dat"
int main()
{
double prices[PRICES_LIST_MAX];
int count = 0;
int i = 0;
FILE *file;
file = fopen(PRICES_FILE,"r");
if(!file)
{
perror("Error opening file");
return -1;
}
memset(prices, 0, sizeof(prices));
while (!feof(file) /* Check for the end of file*/
&&(count < PRICES_LIST_MAX)) /* To avoid memory corruption */
{
fscanf(file, "%lf", &(prices[count++]));
}
fclose(file);
/* Print the list */
printf("Prices count: %d\n", count);
for(i = 0; i < count; i++)
{
printf("Prices[%d] = %lf\n", i, prices[i]);
}
return 0;
}