I am trying to open two files from inside the code, but I am having trouble trying to get my three numbers from first.txt but it only prints the first one. I just need help printing all the numbers from my text file so no need to finish my whole program but advice is welcomed :)!
int main(int argc, char **argv)
{
int *number1Pointer = malloc(80 * sizeof(int));
FILE *file1;
//FILE *file2;
file1 = fopen("first.txt", "r");
//file2 = fopen("second.txt", "r");
int read = fscanf(file1, "%d", number1Pointer);
if(read != '\0')
{
printf("%d", &number1Pointer);
}
else
{
fclose(file1);
}
return 0;
}
int read = fscanf(file1, "%d", number1Pointer); will just read one "%d" like scanf("%d", &num) from stdin.
You can either use a while loop or fscanf(file1, "%d%d%d", ...).
If you need to read 3 numbers, then you could try with this code
int read = fscanf(file1, "%d %d %d", &number1Pointer[0], &number1Pointer[1], &number1Pointer[2]);
The variable read will have the number of elements read or EOF. Hence, the check will have to be adapted.
If your file contains three numbers separated by a space - i.e. 21 32 32 - you need a format string matching that format:
fscanf(file1, "%d %d %d", &number1Pointer[0], &numberPointer[1], &numberPointer[2]);
Remember to free() your allocated variable after using it.
Related
Hi I'm building an app which will check the numbers in the file are all fixed, and if not - to fix them (Depending on specific country codes).
In order to check if the number is good I first need to look at the country code, and for that I need to read the first 3 chars (From a phone number in file) to see if the number even have a country code.
When I'm running the code below I'm getting
Stack around the variable 'country_code' was corrupted".
I think my reading the specific 3 char from the string is making the problem, but I can't find what exactly is doing it.
void fix_file_il_country(char *filename)
{
FILE *f = fopen("1.txt", "r"); //The file to check from
if (f == NULL)
{
printf("EROR\n");
return;
}
FILE *fp = fopen(filename, "w"); //The new file with fixed numbers
if (f == NULL)
{
printf("EROR\n");
return;
}
char num[20];
char country_code[3];
fscanf(f, "%3s %s", &country_code, &num);
while (!feof(f))
{
if (strlen(num) == 12)
if (country_code == "972")
fprintf(fp, "%s\n", num);
fscanf(f, "%3s %s", &country_code, &num);
}
fclose(f);
fclose(fp);
}
The numbers like: 9725XXXXXXXX should be written the new file
Numbers like: 123XXXXXXXXX, or number with more\less chars than 12 shouldn't been written.
You haven't provided space for the null terminator.
char country_code[3];
should be
char country_code[4];
Also, see Why is “while ( !feof (file) )” always wrong?
I can see two potential issues:
the char array needs to store also the null termination, so it should be defined as
char country_code[4]
otherwise it is not possible to define the end of the array.
In the scanf you are passing the pointer of a pointer. You should change
fscanf(f, "%3s %s", &country_code, &num)
to
fscanf(f, "%3s %s", country_code, num)
without the &.
Ive just started c programming.
I would like to read a file of ints which are in a text file in the format
int1(space)int2(space)int3
int4(space)int5(space)int6
int7(space)int8(space)int9
data file example (actually has 25 million lines)
1000002 1 55
1000002 1000006 33
1000002 1000007 8
i am trying to read the numbers and each line i would like to store the 3 ints into a separate variable so i can create a struct with 3 ints per struct. I have a function to create the structs however i don't know how to read the numbers in line by line then assign each 3 ints into a temp variable.
I will be using dynamic allocation to store the structs so just array as temp storage
FILE *fp = fopen("uboss.txt", "r");
//char text[255];
int i = 1;
int a = 1;
int numberArray[9999];
int tmpUI = 0;
int tmpAI = 0;
int tmpPC = 0;
if (fp == NULL)
{
printf("Error Reading File\n");
exit (0);
}
while (!feof(fp))
{
fscanf(fp, "%d ", &numberArray[i]);
printf("Number %d: %d\n",i,numberArray[i]);
tmpUI = numberArray[a];
tmpAI = numberArray[a+1];
tmpPC = numberArray[a+2];
i++;
}
fclose (fp);
You are not the only one asking about this assignment. Try a simpler approach:
In a loop, read each line with fgets(),
Then scan the line for 3 integers with sscanf(str, "%d%d%d", &a, &b, &c); and check the return value, it should be 3.
Finally deal with the values: store them, test them, output them...
There might be extra problems to watch for:
What if the input file contains non numeric values?
What if the values are larger than can fit in the int type.
Its very simple if you know how fscanf works (and returns):
while( fscanf(fp, "%d%d%d", &tmpUI, &tmpAC, &tmpPC) == 3 )
{
...
}
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.
I posted a problem yesterday regarding a certain segment of my code. The aim was to basically scan in data values from a .dat file into an array, print the values whilst also counting how many values were in the file.
Sounds pretty simple, but my program only seemed to print a certain number of the values. More specifically, of a data file containing over 300000 values, it would only print the last 20000 and nothing else.
So I left it, finished the rest of my code and now it's the last part I have to sort. I've made a few changes and tried actually printing an output .dat file now so I can see what I'm getting. The code is below by the way.
Initally I assumed perhaps it was something related to the memory allocation of my array (was getting a segmentation error? when putting the whole code together) so I created an external function that counted the number of values instead (that works).
My only problem now is that it still only chooses to print 20000 values and then the rest are 0s. I was thinking perhaps it had something to do with the type but they all contain 7 dps in scientific notation. Here's a sample of some of the values:
8.4730000e+01 1.0024256e+01
8.4740000e+01 8.2065599e+00
8.4750000e+01 8.3354644e+00
8.4760000e+01 8.3379525e+00
8.4770000e+01 9.8741315e+00
8.4780000e+01 9.0966478e+00
8.4790000e+01 9.4760274e+00
8.4800000e+01 7.1199807e+00
8.4810000e+01 7.1990172e+00
Anyone see where I'm going wrong? I'm sorry for the long question, it's just been bugging me for the last day or so and no matter what I change nothing seems to help. Any kind of input would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
int count(int);
const char df[]="data_file.dat";
const char of[]="output_file.dat";
int main(int argc, char *argv[])
{
FILE *input, *output;
int i, N;
float *array;
N = count(i);
input = fopen(df, "r");
output = fopen(of, "w");
array = (float*)malloc(N*sizeof(float));
if((input != (FILE*) NULL) && (output != (FILE*) NULL))
{
for(i = 0; i < N; i++)
{
fscanf(input, "%e", &array[i]);
fprintf(output, "%d %e\n", i, array[i]);
}
fclose(input);
fclose(output);
}
else
printf("Input file could not be opened\n");
return(0);
}
int count(int i)
{
FILE *input;
input = fopen(df, "r");
int N = 0;
while (1)
{
i = fgetc(input);
if (i == EOF)
break;
++N;
}
fclose(input);
return(N);
}
Your biggest problem is that count() doesn't count float values; it counts how many characters are in the file. Then you try to loop and call fscanf() more times than there are values in the file. The first times, fscanf() finds a float value and scans it; but once the loop reaches the end of file, fscanf() will be returning an EOF status. It seems possible that fscanf() will set the float value to 0.0 when it returns EOF.
I suggest you rewrite so that you don't try to pre-count the float values. Write a loop that just repeatedly calls fscanf() until it returns an EOF result, then break out of the loop and close the files.
P.S. If you are going to write a function like count(), you should pass in the filename as an argument instead of hard-coding it. And your version of count() takes an integer argument but just ignores the value; instead, just declare a temp variable inside of count().
EDIT: Okay, here is a complete working program to solve this problem.
#include <stdio.h>
int
main(int argc, char **argv)
{
FILE *in_file, *out_file;
unsigned int i;
if (argc != 3)
{
fprintf(stderr, "Usage: this_program_name <input_file> <output_file>\n");
return 1; // error exit with status 1
}
in_file = fopen(argv[1], "r");
if (!in_file)
{
fprintf(stderr, "unable to open input file '%s'\n", argv[1]);
return 1; // error exit with status 1
}
out_file = fopen(argv[2], "w");
if (!out_file)
{
fprintf(stderr, "unable to open output file '%s'\n", argv[2]);
return 1; // error exit with status 1
}
for (i = 0; ; ++i)
{
int result;
float x;
result = fscanf(in_file, "%e", &x);
if (1 != result)
break;
fprintf(out_file, "%d %e\n", i, x);
}
return 0; // successful exit
}
Note that this version doesn't need to allocate a large array; it just needs a single temporary float variable. Maybe your program will need to store all the float values. In that case, write a count() function that uses a loop similar to the above loop, using fscanf() to count float values.
Also note that this program checks for errors after calling fopen() and fscanf().
You are allocating far more floats in memory (N) than you need because your N is the number of characters in the file, not the number of values in it.
Also, how did you determine that there are 300000 values in the file?
I just want to output 3 integers from the file. Why this doesn't work? I get -1079184140 and similar.
int main(int argc, char *argv[])
{
FILE* stream = fopen(argv[2], "r");
char line[80];
for (int i = 0; i < 3; i++)
{
fgets(line, 80, stream);
printf("%d \n", line);
}
fclose(streamForInput);
}
I would use sscanf.
int number;
sscanf (line, "%d", &number);
printf ("%d \n", number);
That will pull the first integer on a line. This is not the most secure or robust way, but that is out of scope.
PS:
fclose(streamForInput);
Should be:
fclose(stream);
Hmm. The first problem is:
printf("%d \n", line);
because line is a char[]. But you use a %d to output it, so you output line, which is an address. So printf prints the address of line... instead you coud use printf ("%d", atoi(line));
To print a string, which line is, use %s:
printf("%s \n", line);
Now, if it really were an integer, you could use %d:
int num = atoi(line);
printf("%d \n", num );
What you're seeing is the result of treating a pointer type (which is what a string in C basically is) as an integer type. Since pointers hold memory addresses, that -1079184140 is the actual address the pointer holds, represented as a 32 bit signed integer.
If you know exactly the content of the file (three numbers separated by white space), why not directly read it?
if (fscanf(stream, "%d%d%d", &foo, &bar, &baz) < 3)
// handle error
printf("%d\n%d\n%d\n", foo, bar, baz);
But if you want to read lines, there are already other good answers.
To read a file line by line for integers
void read_file(char *filename, int *readbuff, int size)
{
FILE *fp = fopen(filename,"r");
if(fp == NULL){
printf("Failed to open file %s \n", filename);
return;
}
/*the condition in for loop checks if the integer was read into
readbuff[i] and the readbuff is not overflown*/
for(int i = 0 ; fscanf(fp,"%d\n",&readbuff[i]) == 1 && i < size; ++i);
fclose(fp);
return;
}