writing and reading from file - c

I've written the following snippet to write n random numbers to a file. After writing, I read from the file and store the numbers in an array. The problem I'm facing is that when I read from the file I get extra numbers.
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int limit,i=0;
int numbers[100];
char line[100];
printf("Enter the number of random number to be generated(max 1000)");
scanf("%d",&limit);
FILE *fpi;
fpi=fopen("input.txt","w");
for(i=0;i<limit;i++)
{
fprintf(fpi,"%d\n",rand());
}
fclose(fpi);
FILE *file;
file = fopen("input.txt", "r");
while(fgets(line, sizeof line, file)!=NULL)
{
numbers[i]=atoi(line);
i++;
}
printf("%d\n\n",i);
int totalNums = i;
for (i=0 ; i<totalNums ; i++)
{
printf("%d\n",numbers[i]);
}
fclose(file);
return 0;
}
If I give limit=3 and I write 3 numbers to the file, eg.47,18836,431.
When I read from the file and print it I get 6 values out of which the first 3 are junk and the next 3 are the ones that were written.
If I comment out the writing part and just try to read from the file I get the correct output of only 3 numbers. So I think that there is some problem in my code that writes to the file part.
Can someone help me out with it.

Reset i to 0 before reading from file. e.g.
//your code before
i=0; //reset i
while(fgets(line, sizeof line, file)!=NULL)
{
numbers[i]=atoi(line);
i++;
}
//your code after

Related

Read Values from a file and store it in 2D matrix

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'm supposed to read a text from a .txt and display it in the console but my code is not working,where is my mistake?

Firstly, I'm asked to type a text in the console and print it in a .txt file. Then,after I've printed that text in the .txt file,I'm supposed to print that text in the console and by the end of each line to show how many characters each line have.
ex:
Annie is a 8
big girl 7
with big dreams 13
for (int i=0; i<4 ;i++)
{
while ((c=fgetc(p))!=EOF||(c=fgetc(p))!='\n')
{
printf("%c",c);
n++;
}
printf("%d",n);
}
This part is the problematic one. After I've input the text and print it in the .txt file, I've tried to print out character by character in the console and the "n" variable should be the counter of each letter. Where is my mistake? I can show the whole code if needed.
Didn't you forget rewind (or fseek) instruction ? If you write the .txt file and after you try to read it without rewind (or fseek or close/fopen) instruction, the file position is at the end of the file. So there is not char to read because you are already at the end of file. Try the following code with and without the rewind instruction.
#include <stdio.h>
#include <stdlib.h>
int main() {
char c = '\0';
int n;
FILE * p;
p=fopen("myfile.txt","w+");
fprintf(p,"Annie is a\nbig girl\nwith big dreams");
rewind(p);
while((c=fgetc(p))!=EOF) {
if (c=='\n') {
printf(" : %d\n",n);
n=0; }
else {
printf("%c",c);
if (!isspace(c)) n++;
}
}
printf(" : %d\n",n);
}
Please make your question clear. What does not work, is n displaying the wrong number of characters or what is your problem?
This little code sample should work if only n is displaying the wrong number:
char c = ''; //so in default it is empty
for (int i=0; i<4 ;i++)
{
int n=0;
while( (c=fgetc(p))!=EOF && c!='\n')
{
printf("%c",c);
if(c!=' ')//so we only count the letters and not whitespaces
n++;
}
printf("%d",n);
}
This should give your desired result when your file opening part works.

C: Output error linked-lists and writing to and reading from file

Im trying to create a linked list containing numbers and write those numbers to a file, and then read the same file and read the data within the file and print those numbers.
What I think the problem is, is that there's something wrong when reading the file.
I've added som print statements for debugging, and when printing what I'm writing to the file, it looks ok. But when I'm reading the file and printing I get the first number the user entered printed twice.
ex:
input: 1,2,3
output:3,2,1,1
I don't really know if there's a problem with my linked list, writing to file or if it's the reading. So I would appreciate any kind of input that would help me to better understand.
Thanks
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct postTyp
{
int num;
struct postTyp *next;
}postTyp;
FILE *fp;
int main()
{
postTyp *l, *p; //l=list , p=pointer
l = NULL;
p=malloc(sizeof(postTyp));
//Creates linked list until user enters 0
printf("Enter a number, 0 to exit: ");
scanf("%i", &p->num);
while (p->num != 0)
{
p->next=l;
l=p;
p=malloc(sizeof(postTyp));
printf("Enter a number, 0 to exit: ");
scanf("%i", &p->num);
}
free(p);
p=l;
//write the linked list to file
fp = fopen("test.txt", "w");
while(p->next != NULL)
{
printf("%2i", p->num);
fwrite(p, 1, sizeof(postTyp), fp);
p=p->next;
}
printf("%2i", p->num);
fwrite(p, 1, sizeof(postTyp), fp);
fclose(fp);
printf("\n");
//Code below to read the file content and print the numbers
fp = fopen("test.txt", "r");
fread(p,sizeof(postTyp),1,fp);
fseek(fp,0,SEEK_SET);
//The first number entered at the beginning, will be printed twice here.
while(!feof(fp))
{
fread(p,sizeof(postTyp),1,fp);
printf("-----\n");
printf("%i\n", p->num);
}
fclose(fp);
return 0;
}
From the fread manual (https://linux.die.net/man/3/fread):
fread() does not distinguish between end-of-file and error, and callers must use feof(3) and ferror(3) to determine which occurred.
So, you have to check the fread return value before printing p->num.

How to write strings in different places of a file in C

in the code below:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char const *argv[])
{
FILE *fp ;
fp = fopen("out.txt", "r+");
int count = 1;
char ch ;
char userInput[5] ;
int lineNumber = 0;
while (lineNumber!= -1){
fgets(userInput, sizeof(userInput), stdin);
lineNumber = atoi(userInput);
while((ch=fgetc(fp))!=EOF)
{
if(ch=='\n') //counts number of lines
count++;
if(count == lineNumber)
{
fprintf(fp, "writed %d\n", count);
fseek(fp, 0, SEEK_SET);
}
}
}
return 0;
}
I want to write a string in the line which the user gives me,i store the user answer in userInputand then convert it to the int and store it in lineNumber.
when i try to write fore example in line 90 (my file has 100 lines) two error i get:
1.the file reduce to a 91-line file (instate of remain 100 lines)
2.although i seek to first of file,no more lines written in the next loops and user inputs.
Reading a file (to count its lines) and then turning around and writing to it is tricky. Among other things, you have to do something like an fseek between the reading and the writing. So try interchanging the order of the fseek and fprintf calls:
fseek(fp, 0, SEEK_SET);
fprintf(fp, "writed %d\n", count);
Also, be aware that unless the new text you're writing ("writed ###") is exactly the same length as whatever line used to be there, the line structure of the remainder of the file is likely to get garbled.
See also this question in the C FAQ list.

Read a file then store numbers in array C

so I have this file called "score.txt" with contents
NAME
20
NAME2
2
And I'm using this code but it gets an error and I have no idea on how to put the integers from the file in an array.
int main(){
FILE* file = fopen ("score.txt", "r");
int i = 0;
fscanf (file, "%d", &i);
while (!feof (file))
{
printf ("%d ", i);
fscanf (file, "%d", &i);
}
fclose (file);
system("pause");
}
I'm only self learning and i've been trying to figure this out for 2hours already
The problem with using fscanf for input where some lines will fail the format is that the file will not be advanced per iteration of the while loop, so you get stuck.
You can get a solution by using fgets to grab the data and sscanf to grab the number:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main(void) {
int i = 0;
int ret = 0;
char buf[50];
FILE *file = fopen("score.txt", "r");
if (file == NULL) {
fprintf(stderr,"Unable to open file\n");
exit(1);
}
while (fgets(buf,sizeof(buf),file)) {
ret = sscanf(buf,"%d",&i);
if (ret == 1) { // we expect only one match
printf("%d\n", i);
} else if (errno != 0) {
perror("sscanf:");
break;
}
}
fclose(file)
return(0);
}
This will output, for your input:
20
2
We check the output of sscanf as it tells us if the format has been matched correctly, which will only happen on the lines with integer, and not the 'NAME' lines. We also check for 'errno' which will be set to non-zero if sscanf encounters an error.
We used char buf[50]; to declare a char array with 50 slots, which fgets then uses to store the line its reading; however if the line is more than 50 chars in length it will be read in 50 char chunks by fgets, and you may not get the results you desire.
If you wish to store the integers you read into an array, you'll have to declare an array, then on each read assign a slot in that array to the value of the int you read i.e. int_array[j] = i (where j will have to change with each slot you use). I'll leave it as an exercise to implement this.

Resources