Getting gibberish values in files when putw() is used - c

Program to take integer input from user and store them in a file, then sort the integers into two different files (odd and even), when I used fprintf it overwrites the previous value thats why I tried putw() but I am getting gibberish values in files
This is my code:
#include<stdio.h>
int main()
{
int n,a[50];
printf("\nEnter no of entries:");
scanf("%d",&n);
FILE *f1,*f2,*f3;
f1=fopen("Numbers.txt","w+");
for(int i=0;i<n;i++)
{
printf("\nEnter a number:");
scanf("%d",&a[i]);
putw(a[i],f1);
}
fclose(f1);
f1=fopen("Numbers.txt","r");
for(int i=0;i<n;i++)
{
if(a[i]%2==0)
{
f2=fopen("EvenNum.txt","w+");
putw(a[i],f2);
fclose(f2);
}
else
{
f3=fopen("OddNum.txt","w+");
putw(a[i],f3);
fclose(f2);
}
}
}

That's not what putw does. putw writes an int in binary not as text. Do you mean fprintf(f1, "%d", a[i]);?
The man page for getw and putw says to use fread and fwrite instead, which doesn't seem to fit here.
f1=fopen("Numbers.txt","w+"); will clobber the file. Do you want "a+" to append?

Related

I'm trying to write a specific number of lines in a file but I keep getting a blank line as the first one

i'm new here and i'm trying to solve a FILE problem in c. Basically i have to create a program that lets the user input how many lines he wants to write in a file, create a new file, write those lines and the reading it and establish how many lines where written and print the number of lines.
int main() {
int x, lc=0;
char str[100];
FILE *fp=fopen("test.txt","w");
if (fp==NULL) {
printf("\nOpening failed");
}else{
printf("\nOpened correctly");
}
printf("\nStrings to write:\n");
scanf("%d",&x);
for (int i = 0; i < x; i++) {
fgets(str, sizeof str, stdin);
fputs(str,fp);
}
fclose(fp);
FILE *fr=fopen("test.txt", "r");
while (fgets(str, 100, fr)!=NULL) {
lc++;
}
fclose(fr);
printf("\nThere are %d lines",lc);
return 0;
}
If i leave the code like this it messes up with my for cycle and it only lets me write 3 lines because it does put a free line at the start of the file. Can you explain how do i solve that? or if it's just how fgets and fputs behave and i have to remember that blank line at the start. Thank you in advance. (i'll leave a file output as follows with numbers for the lines)
1)
2)it seems to work
3)dhdhdh dhdh
4)random things
As you can tell from the comments, there are a lot of ways to approach this task. The usage of "scanf" and "fgets" can get complex especially if mixed within the same reading task. But, just to give you one option as to deriving a solution, following is a snippet of code to offer one of many possible routes.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int x, lc=0;
char str[101];
FILE *fp=fopen("test.txt","w");
if (fp==NULL)
{
printf("Opening failed\n");
}
else
{
printf("Opened correctly\n");
}
printf("Strings to write: ");
scanf("%d",&x);
for (int i = 0; i < x; i++)
{
printf("Enter string: ");
scanf("%s", str);
fprintf(fp, "%s\n", str);
}
fclose(fp);
FILE *fr=fopen("test.txt", "r");
while (fgets(str, 100, fr)!=NULL)
{
lc++;
}
fclose(fr);
printf("\nThere are %d lines\n",lc);
return 0;
}
You will note that both "scanf" and "fgets" are being used in this example, but not in reference to the same file. For user input, "scanf" is getting used. Once the file is closed and then reopened for reading, "fgets" is being used for that portion of the task.
Testing this program snippet out resulted in matching up the same quantity of lines read from the file as were entered.
#Una:~/C_Programs/Console/FileWrite/bin/Release$ ./FileWrite
Opened correctly
Strings to write: 4
Enter string: Welcome
Enter string: to
Enter string: Stack
Enter string: Overflow
There are 4 lines
Give it a try and see if it meets the spirit of your project.

Trying to sum values from a text file, receiving unrecognized character as output?

Using C, I am trying sum up the numbers in a file. The file contains numbers such as:
123
456
788
...
356
When running the code, it properly asks for input and prints the number I enter. However, it does not sum the file, and just displays an unrecognized character symbol, like a small ?. I don't think the number is over the alloted INT_MAX_SIZE. What seems to be the issue?
#include <stdio.h>
main() {
//Number variable to assign each line to
int c;
int fds[2];
int childid;
int size;
int number;
int sum;
printf ("Enter the number of processes to create: ");
scanf ("%d", &number);
printf ("You entered: %d", number);
printf("\n");
//File I/O operations
FILE *file;
//Open file for reading
file = fopen("Project1_OS/project1_data/file1.dat", "r");
//If file is found
if (file) {
//While file has data to be read
while ((c = getc(file)) != EOF)
//Print data
//putchar(c);
sum+=c;
//Close the file I/O
fclose(file);
}
putchar(sum);
}
first getc it's a function for reading characters from a file not integers .
you have to use fscanf :
fscanf(file,"%3d",&c)
second putchar it's a function for printing characters not intgers .
so you have to write :
printf("%d",sum);

What's the error in this code?(C - File Handling)

What I want to do is to write n(taken from user) elements to a file.Then read the elements again to an array and sort them and again write them in another file.
Finally open that file and display its contents.
But the code seems not to work, all syntax, grammar etc is checked what's the error??
#include<stdio.h>
struct data
{
int a,ar[100];
}e;
int main()
{ FILE *f1,*f2;
int i,j,n,t;
printf("\nEnter Array Size:");
scanf("%d",&n);
f1=fopen("Array.txt","w");
for(i=0;i<n;i++)
{ printf("\nEnter %d element:",i+1);
scanf("%d",&e.a);
fprintf(f1,"%d",e.a);
}
fflush(stdin);
fclose(f1);
rewind(f1);
i=0;
f1=fopen("Array.txt","r");
while((fscanf(f1,"%d",&e.ar[i++]))!=EOF)
{}
fclose(f1);
for(i=0;i<n;i++)
{ for(j=0;j<n-1;j++)
{ if(e.ar[j]>e.ar[j+1])
{ t=e.ar[j];
e.ar[j]=e.ar[j+1];
e.ar[j+1]=t;
}
}
}
f2=fopen("Sort.txt","w");
i=0;
while((fprintf(f2,"%d",e.ar[i]))!=EOF)
{ i++;}
fclose(f2);
f2=fopen("Sort.txt","r");
while((fscanf(f2,"%d",&e.a))!=EOF)
{ printf("%d ",e.a);
}
fclose(f2);
return 0;
}
So you want to know the error? I found a HUGE one.
As I was running your program, I have determined a segmentation fault occurs after this line:
f2=fopen("Sort.txt","w");
The major error here is that you opened a file for writing data to it, but you're making a rather confusing loop.
This is your code:
i=0;
while((fprintf(f2,"%d",e.ar[i]))!=EOF)
{ i++;}
In the state it is in, the value of i will exceed the upper bound value of your ar int array. You set the upper bound value to 100, but in the while loop, it will run endlessly until segmentation fault happens (when i goes past 100) because fprintf will never return an EOF (according to what the linux manual on fprintf claims).
What I would suggest instead is this:
for(i=0;i<n;i++){
fprintf(f2,"%d",e.ar[i]);
}
where n is the number of elements to finally print (as indicated by user at beginning of the program).

I want to make Sort program using File input/output with C language

I want to make 'Merge sort' Program.
When i started it "arr.txt" and "brr.txt" are just data and "result.txt" is result of merge sort (arr.txt+brr.txt) .
#include<stdio.h>
#include<stdlib.h>
void merge_sort(int num)
{
FILE *fp1,*fp2,*fp3; // fp1 is arr.txt, fp2 is brr.txt, and fp3 is result.txt
int i, j, point_one=0, point_two=0;
char a[num], b[num], c[num];
fp1=fopen("arr.txt","r");
fp2=fopen("brr.txt","r");
fp3=fopen("result.txt","w");
fscanf(fp1, "%s", a);
fscanf(fp2, "%s", b);
for(i=0;i<num;i++)
{
if(a[point_one]>b[point_two])
{
fprintf(fp3, b[point_two]);
point_two++;
}
else
{
fprintf(fp3, a[point_one]);
point_one++;
}
}
fclose(fp1);
fclose(fp2);
fclose(fp3);
}
int main(void)
{
FILE *fp_one,*fp_two;
char *arr;
char *brr;
int num;
fp_one=fopen("arr.txt","w");
fp_two=fopen("brr.txt","w");
printf("input array size :");
scanf("%d", &num);
arr=(char*)malloc(sizeof(char)*num);
brr=(char*)malloc(sizeof(char)*num);
printf("input arr :" );
scanf("%s", arr);
printf("input brr :");
scanf("%s", brr);
fprintf(fp_one, arr);
fprintf(fp_two, brr);
merge_sort(num);
fclose(fp_one);
fclose(fp_two);
free(arr);
free(brr);
return 0;
}
But, in this code, I can't play sorting. Please help me
++
if array size is 5, arr.txt's contents are "acfj",and brr.txt's contents are "bdgh",
the result.txt's contents are "abcdfgh"
You have two problems. The first is that you don't print the letters correctly. The fprintf function expects the second argument to be a string, but you pass it a single character. The compiler should be screaming warnings about this to you. You should never disregard warnings, as they often are indicators of undefined behavior.
Either use e.g. fputc or use the correct format string to print a character.
The second problem, is that you don't loop enough times for the sorting/merging to be complete, as well as you never check for the end of either input.
You should close fp_one and fp_two before calling merge_sort(). Otherwise the previous output may haven't been flushed into file yet.
According to your test input, you tried to store 5 characters into 3-element character array (don't forget the '\0' character terminating a string). This leads to buffer overflow, which in turn leads to undefined behavior.
Yet another problem: in merge_sort(), when either point_one or point_two reaches the end of string, the next comparison always pick '\0' which is smaller than all other characters.
at main
change to
fprintf(fp_one, "%s", arr);//to prevent malfunction when '%' is included
fprintf(fp_two, "%s", brr);
fclose(fp_one);//to determine the output of the file.
fclose(fp_two);//Also Close to open the file in the merge_sort function.
merge_sort(num);
merge_sort change to
void merge_sort(int num){
FILE *fp1,*fp2,*fp3;
int point_one=0, point_two=0;
char a[num], b[num];
fp1=fopen("arr.txt","r");
fp2=fopen("brr.txt","r");
fp3=fopen("result.txt","w");
fscanf(fp1, "%s", a);
fscanf(fp2, "%s", b);
fclose(fp1);
fclose(fp2);
while(a[point_one] && b[point_two]){//Data of both is valid
if(a[point_one]>b[point_two]){
fprintf(fp3, "%c", b[point_two++]);
} else {
fprintf(fp3, "%c", a[point_one++]);
}
}
if(a[point_one]){//There is a rest.
fprintf(fp3, "%s", &a[point_one]);
}
if(b[point_two]){
fprintf(fp3, "%s", &b[point_two]);
}
fclose(fp3);
}

how to store and read data from files

I am new to C in linux. I am trying to store data to file and read them back. Is this the correct way. When I try to compile this i am getting errors. Can anyone help me please. thanks in advance.
#include<stdio.h>
typedef struct
{
int select;
char lastname[25];
char firstname[25];
char address[25];
char phonenumber[25];
} addressbook;
addressbook a[5];
FILE *fp;
int main()
{
int i;
for( i=0; i<5 ; i++)
{
printf("enter details\n");
printf("enter lastname:\n");
scanf("%s", a[i].lastname);
printf("enter firstname:\n");
scanf("%s", a[i].firstname);
printf("enter address:\n");
scanf("%s", a[i].address);
printf("enter phone number:\n");
scanf("%s", a[i].phonenumber);
fp = fopen("addressbook.dat","a+");
fwrite(&a, sizeof(a), 1, fp);
fclose(fp);
}
for(i=0; i<5; i++)
{
fopen("addressbook.dat", "r");
fread(&a, sizeof(a), 1, fp );
printf("lastname:%s\n", a[i].lastname);
printf("firstname:%s\n", a[i].firstname);
printf("address:%s\n", a[i].address);
printf("phonenumber:%s\n", a[i].phonenumber);
fclose(fp);
}
return 0;
}
i am not getting any output. it was blank.
Check out this code, and let me explain you what all was wrong in your code.
#include<stdio.h>
typedef struct
{
int select;
char lastname[25];
char firstname[25];
char address[25];
char phonenumber[25];
} addressbook;
#define ARRAYLEN 2
addressbook a[ARRAYLEN];
FILE *fp;
int main()
{
int i;
fp = fopen("addressbook.dat","a+");
for( i=0; i<ARRAYLEN ; i++)
{
printf("enter details\n");
printf("enter lastname:\n");
scanf("%s", a[i].lastname);
printf("enter firstname:\n");
scanf("%s", a[i].firstname);
printf("enter address:\n");
scanf("%s", a[i].address);
printf("enter phone number:\n");
scanf("%s", a[i].phonenumber);
fwrite(&a[i], sizeof(a), 1, fp); /* notice, array indexed */
}
fclose(fp);
fopen("addressbook.dat", "r");
for(i=0; i<ARRAYLEN; i++)
{
fread(&a[i], sizeof(a), 1, fp );
printf("lastname:%s\n", a[i].lastname);
printf("firstname:%s\n", a[i].firstname);
printf("address:%s\n", a[i].address);
printf("phonenumber:%s\n", a[i].phonenumber);
}
fclose(fp);
return 0;
}
Actually, your code as-is (apart from the edit you've already done) isn't so incorrect, but it had some small yet crucial flaws.
The only real change is this :-
fwrite(&a[i],...
and,
fread(&a[i],...
i.e. pass the address of the particular array-element that you want to write, not the entire array. Also, even though you were passing address of the entire array, the no. of byte/characters you were asking library to write, was just sizeof(thestructure), so essentially the remaining was truncated. Without that, what you were writing into the file was something like...
A <-- file contents after, first iteration
AAB <-- file contents after, second iteration
AABABC <-- file contents after, third iteration
AABABCABCD <-- file contents after, fourth iteration
....
I think you'd figure out from that, what was wrong. Also the contents of your addressbook.dat was text, so a simple "cat addressbook.dat" (on Linux) would have told you what was wrong :-)
You are opening and closing file in every iteration. Now this is not an error, but just a sub-optimal thing, and quite likely to be something you do not want to do. File operations are costly, and opening/closing those cost quite a few CPU cycles. You are better off, opening file once for all writes, and once for reads. (Of course, once can remove the fclose() done after write-block and fopen() done before read-block as well, by just getting the file-pointer to the beginning of file -- left as an exercise for you).
While testing, no one wants to enter so much data. So I've added a #define (and with a newer compiler you can replace it with a const definition as well), that defines a macro which holds the addressbook array size. For testing, I keep it at "2". For production you can just change that value to "1000" and it will still work. Again, this wasn't an error, just a better style, if you will.
Oh, and BTW, pls get your indentation right. Are you coming from Python world ? Or it could be an artifact of the indentation required by SO for posting code-blocks.
HTH
It seems to me that you are not including the required headers. For example, printf requires stdio.h, so at the beginning for your file, you will need
#include <stdio.h>
CPlusPlus.com provides pretty good and easy to search documentation for C, so if you wish to use a function, you can look it up and find out which header is required.

Resources