This is a very simple question, but I can't seem to find something about it in here already. I want to read two integers from a file with C. My code now is this:
int main() {
FILE *fp;
int s[80];
int t;
if((fp=fopen("numbers", "r")) == NULL) {
printf("Cannot open file.\n");
} else {
fscanf(fp, "%d%d", s, &t);
printf("%d %d\n", s[0], s[1]);
}
return 0;
}
I get the first integer from the file, but the next one is just a random number. My file is like this:
100 54
Thanks in advance
This line:
fscanf(fp, "%d%d", s, &t);
is putting one of the ints in s[0] and the other in t, but you are printing out s[0] (which is your first int) and s[1], which is uninitialized (and hence "random").
You are reading the results into s and t but printing only s ?
Your problem is on this line:
fscanf(fp, "%d%d", s, &t);
printf("%d %d\n", s[0], s[1]);
You're reading into s[0] and t, but printing s[0] and s[1]. Either of the following would work as a replacement:
fscanf(fp, "%d%d", s, &t);
printf("%d %d\n", s[0], t);
Or:
fscanf(fp, "%d%d", &s[0], &s[1]);
printf("%d %d\n", s[0], s[1]);
You never initialize it. You pass pointer to s, which means (here) the first element, as a first parameter. What do you expect to show up in s[1]?
When you are doing the fscanf, you are using one set of variables.
But when you do the printf, you are using another.
One way to get it working correctly:
#include "stdio.h"
int main()
{
FILE *fp;
int s[80];
if((fp=fopen("numbers", "r")) == NULL) {
printf("Cannot open file.\n");
} else {
fscanf(fp, "%d%d", &s[0], &s[1]);
printf("%d %d\n", s[0], s[1]);
fclose(fp);
}
return 0;
}
You need to read into &s[0] and &s[1] or print out s[0] and t.
Related
My code is given below. If run this code then even though the text file gets created correctly, for some reason junk values get printed in the console. When I include the string then only the string gets read and printed correctly in the console window and I get junk value for the rest of the variables but when I remove the string completely then I get correct values for rest of the variables. Why is this issue occurring and how to fix it ?
This is the code:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char str[] = "a string";
char str2[50];
char ch ='a';
char ch1;
int num = 12;
int num1;
float deci = 51.15;
float deci1;
FILE *new;
new = fopen("a.txt","w");
if (new == NULL) {
printf("Error! file not found! \n");
}
fprintf(new, "%s\n", str);
fprintf(new, "%c\n", ch);
fprintf(new, "%d\n", num);
fprintf(new, "%.2f\n", deci);
fclose(new);
new = fopen("a.txt", "r");
if (new == NULL) {
printf("Error! file not found! \n");
}
fscanf(new, "%[^\n]s", str2);
//str2[7]='\0';
fflush(stdin);
fscanf(new, "%c", &ch1);
fscanf(new, "%d", &num1);
fscanf(new, "%f", &deci1);
//fclose(new);
printf("string: %s character: %c integer: %d float: %f", str2, ch1, num1, deci1);
//enter code here
fclose(new);
}
If I'm not wrong the error is here:
fscanf(new, "%[^\n]s", str2);
Try to change it with:
fscanf(new, "%[^\n]\n", str2);
This does work for me.
For example: #1 Tutti/Leeloo/853811356; N
And this is my code:
typedef struct{
int redni;
char prezime[50+1];
char ime[50+1];
char osobna[50+1];
char glasao[10];
} Biraliste;
int nBiraci=0;
while(fscanf(biralisteTxt, "%d %[^/]/%[^/]/%[^;];%[^\n]",
biraci[n].redni, biraci[n].prezime, biraci[n].ime, biraci[n].osobna, biraci[n].glasao ) == 5)
{
nBiraci++;
}
for(i=0;i<nBiraci;i++)
{
fprintf(statistikaTxt, "%d %s %s %s %s",
&biraci[i].redni, biraci[i].prezime, biraci[i].ime, biraci[i].osobna, biraci[i].glasao );
}
Can someone help mi with right fscanf and fprintf, and is it ok to fscanf redni with %d or it should be %s.
" #%d %[^/]/%[^/]/%[^;];%[^\n]" - this is the right answer, thank you
The following code fixes two problems.
scanf must get the address of the variable to fill, this &biraci...
the index must be nBiraci and not n, thus &biraci[nBiraci]...
there must be a # in front of %d
int nBiraci=0;
while(fscanf(biralisteTxt, " #%d %[^/]/%[^/]/%[^;];%[^\n]",
&biraci[nBiraci].redni, (char*)&biraci[nBiraci].prezime,
(char*)&biraci[nBiraci].ime, (char*)&biraci[nBiraci].osobna,
(char*)&biraci[nBiraci].glasao) == 5)
{
nBiraci++;
}
I am scanning from a file into parallel arrays.
I successfully scan the strings, but the ints and floats do not scan correctly!
What is going wrong here???
Num, human, and cool are arrays declared in the main function.
An example of a record in hello.txt:
Angela, Merkel, 50, 10, 9.1
void read(int *lines, char first[ENTRY][FIRST], char last[ENTRY][LAST], int *num, int *human, float *cool)
{
FILE *ifile;
int i;
ifile = fopen("hello.txt", "r");
fscanf(ifile, "%[^,] %*c %[^,] %*c %d %*c %d %*c %f", first[0], last[0], &num[0], &human[0], &cool[0]);
printf("%s", first[0]);
printf("%s\n", last[0]);
printf("%d\n", num[0]);
printf("%d\n", human[0]);
printf("%f", cool[0]);
fclose(ifile);
}
Try
fscanf(ifile, "%[^,] %*c %[^,] %*c %d %*c %d %*c %f", first[0], last[0], num, human, cool);
First, with scanf family of functions, a space matches any amount of white space, including none, in the input, also don't use %*c, it is not necessary. Second, you need to specify the comma in format string to successfully scan the fields. Third, when you scanf always check its return value to make sure the expected number fields were input. Try this fix:
void read(int *lines, char first[ENTRY][FIRST], char last[ENTRY][LAST], int *num, int *human, float *cool)
{
FILE *ifile;
ifile = fopen("hello.txt", "r");
if (ifile == NULL) return;
int ret = fscanf(ifile, "%[^,], %[^,], %d, %d, %f", first[0], last[0], &num[0], &human[0], &cool[0]);
if (ret != 5) { // input file does not match the format
return;
}
printf("%s ", first[0]);
printf("%s\n", last[0]);
printf("%d\n", num[0]);
printf("%d\n", human[0]);
printf("%f\n", cool[0]);
fclose(ifile);
}
In this program, I am attempting to read a name and their GPA from a file. The first name is Audrey, then a white space, and then 3.6.
The second line is Oakley, then a white space, and 3.5.
int main()
{
FILE * fPtr;
FILE * fPtr2;
char x[10] = { "Oakley " };
double y;
int z;
fPtr = fopen("data.txt", "r");
if (fPtr == NULL) // open failure
puts("File open for read failed");
else
{
while (scanf("%d", &z) != EOF)
{
fscanf(fPtr, "%s", x);
fscanf(fPtr, "%lf", &y);
fprintf(stdout, "Value read = %s\n", x);
fprintf(stdout, "GPA = %lf \n", y);
}
}
fclose(fPtr);
system("pause");
return 0;
}
So, I tried this once before and it worked. In that attempt, "x[10] = Audrey" and this was the first name in the list. It worked, and the fscanf gave me her GPA. The second time, I tried scanning for Oakley and I still get Audrey, but when I remove that line I get a really large negative number.
I used fscanf because it tokenizes around whitespace, so my theory is that if the cursor gets to the proper name then it will read the next number and that will be the GPA? Right? How do I get it to search for Oakley?
You need check scanf for any errors, which could happen because the input file does not match the format you specified. Try these changes:
char user[100];
while (scanf("%s", user) == 1) {
while (fscanf(fPtr, "%s %lf", x, &y) == 2)
{
if (strcmp(user, x) == 0) {
fprintf(stdout, "GPA for %s is %lf \n", user, y);
break;
}
}
rewind(fPtr);
}
Also, fPtr2 is is uninitialized in your code, remove the line fclose(fPtr2).
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);
}