C - Reading Till The EOF, Getting Additional Addresses and Numbers (Array) - c

So, I have a File full of numbers:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
The case is, I don't know the exact number of numbers in this file, so I don't know the exact size of array I will need to write this file info in to this array.
I just gave array much bigger size than I need and I will show you the output, partially it does its job.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#define ARR_SIZE 30
int main(void){
FILE *fp;
int array[ARR_SIZE];
fp = fopen("C:/project/project.txt", "r");
printf("Numbers: ");
for(int i = 0; i < ARR_SIZE; i++){
fscanf(fp, "%d", &array[i]);
}
for(int j = 0; j < ARR_SIZE; j++){
printf("\n%d", array[j]);
}
fclose(fp);
return 0;
}
I am just trying to do standard things, opening file, reading file with for loop, writing all this info to array and outputting array.
Here is the output I get, I understand it is because of the size, but can you tell me how to limit all of these? Easiest way?
Output:
Numbers:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
4199136
0
4200896
6422240
6422296
6422476
1998244384
592257989
-2
1998220218
1998220461
4200896
6422368
4200987
4200896
I have array size 30 and numbers in the file 15, first 15 is okay, it is exactly what I need, but I don't need those number after it...

You need a stop-condition for the loop that reads from the file. One option is to stop when you can't scan an item. Use the return value from fscanf to detect that.
When you do the printing only print the number of items actual scan'ed.
Try
for(int i = 0; i < ARR_SIZE; i++){
if (fscanf(fp, "%d", &array[i]) != 1) break; // Stop if the scan fails
}
for(int j = 0; j < i; j++){ // ARR_SIZE replaced by i
printf("\n%d", array[j]);
}
BTW: You should check that fp is valid just after the file open.

Related

Can i fflush multiline output?

Is there any way that I can fflush() a multi-line output? For example, if I wanted to print a 5x5 array in 5 separate lines and shuffling it multiple times every 1 second, how am I supposed to use fflush()?
#include <stdio.h>
#include <stdlib.h>
int main(){
int arr[5][5]; //Just an array of numbers
for(int k = 0; k < 10; k++){
for(int i = 0; i < 5; i++){
for(int j = 0; j < 5; j++){
printf("%d ", arr[i][j]);
}
printf("\n");
}
fflush(stdout);
shuffle(arr);
sleep(1);
}
return 0;
}
This how i would want the output to change (without of course creating any additional new lines):
0 1 2 3 4 5 3 12 7 8
6 7 8 9 10 -> 1 2 0 13 6
. .
. .
. .
I tried both rewind(stdout) and fsetpos() but it didn't seem to do anything.
What you want is called clearing the display. You can do
system("cls"); on Windows or system("clear"); on Unixy systems.
Or there are https://en.wikipedia.org/wiki/ANSI_escape_code - if you print those special characters, stuff will happen, you can move the cursor to the top and overwrite the text or try just clearing the screen.
I'm not confident which escape code will work for you, experiment.

Scanning numbers from a file into a two dimentional array

I am new to programming so I apologize if I mess up on anything.
So I am trying to scan a file with multiple lines of numbers and put them into a two dimensional array. I've tried looking at other questions relating to this and nothing has worked so far.
So I have tried using nested loops to scan the array and put the numbers inside but nothing seems to happen.
Inside the txt file is as follows:
0 7 9 4 0 0 8 0 4 5 0 1
0 2 4 0 0 0 1 6 2 8 6 0
0 1 1 1 1 0 8 5 6 8 0 7
0 5 1 0 0 0 1 3 8 1 0 1
Every 12th number is a new line.
#include <stdio.h>
#define BUF_SIZE 12
#define ROW 4
#define COL 12
void
barcodeArray(int barcode[ROW][COL])
{
char buffer[BUF_SIZE];
FILE* f = fopen("q5_input.txt","r");
if(f == NULL)
{
printf("no such file.");
}
for(int k = 0; k < ROW; k++)
{
for(int j = 0; j < COL; j++)
{
fscanf(f, "%1d", &barcode[k][j]);
printf("%ls", &barcode[k][j]);
}
}
fclose(f);
}
int
main(void)
{
int barcode[ROW][COL];
barcodeArray;
}
The printf inside the for loops is just reading back the numbers as it inputs the numbers in the array. As the code is it compiles but does nothing.
You must call your function with argument barcodeArray(barcode);
Edit : If you are not sure of the size of the array you can take a look at dynamically allocated variables. This is an important part of C programming
Try this way. I think using freopen() is easier and hassle free. It enables you to use same I/O functions that you use for console I/O operations.
#include <stdio.h>
#define BUF_SIZE 12
#define ROW 4
#define COL 12
void barcodeArray()
{
int barcode[ROW][COL];//This can be declared inside the function.
char buffer[BUF_SIZE];
FILE* f=freopen("q5_input.txt","r",stdin);
if(f == NULL)
{
printf("no such file.\n");
return;
}
for(int k = 0; k < ROW; k++)
{
for(int j = 0; j < COL; j++)
{
scanf("%d",&barcode[k][j]);
printf("%d ",barcode[k][j]);
}
printf("\n");
}
fclose(f);
}
int main(void)
{
barcodeArray();
}
Additionally if you want to output it in a file you can do the following in the main function:
int main(void)
{
freopen("out.txt","w",stdout);
barcodeArray();
}

Basic C help using arrays

Basically I'm trying to read from a text file which I created. I have a header of value 5, indicating that the rest of the file contains the data for 5 separate auctions.
The next line contains a value of 4, indicating 4 bids in the first auction.
The four integers after that represent bids in the auction. Here's the entire text file:
5
4
80 70 100 270
2
8 7
1
800
7
90 81 72 685 49 50
4
800 900 785 600
Basically, I need to figure out the largest of the bid values for each auction. I can probably do that on my own, but I'm really stuck when it comes to representing those bid values as an array.
Here's my code so far:
#include <stdio.h>
int main()
{
int header, i, j, cur_val, auction[cur_val];
FILE *ifp;
ifp = fopen("input.txt", "r");
fscanf(ifp, "%d", &header);
for (i = 0; i < header; i++) {
fscanf(ifp, "%d", &cur_val);
printf("%d\n", cur_val);
for (j = 0; j < cur_val; j++) {
fscanf(ifp, "%d", &auction[cur_val]);
printf("%d\n", auction[cur_val]);
}
printf("\n");
}
//printf("Auction %d was sold for ");
fclose(ifp);
return 0;
}
If I create auction without the array then it prints the values but I have no way of accessing each individual value in order to determine the max value. How can I get the "bidding" values to act as an array of values? Using this code just crashes my entire program.

Get a certain number of elements into an Array

This is my code so far:
#include "stdafx.h"
#define SIZE 200
int _tmain(int argc, _TCHAR* argv[])
{
FILE * ifp = NULL;
int inputArray[SIZE];
int i, j;
int c;
ifp = fopen("testfile.txt", "r");
for (i = 0; i <= SIZE; ++i)
fscanf(ifp, "%d", &inputArray[i]);
/*fscanf(ifp, "%d", */
for (i = 0; i <= SIZE; i++)
printf("%d", inputArray[i]);
return 0;
}
So I have a file that has nnumbers in it like:
3
5 5 3
6
3 2 6 4 1 1
The code above seems to work in getting the numbers into an array like 3 5 5 3 6 3 2...etc.
But then, the array size is 200. So the rest of the space not used in the array isn't just blank. It has a huge, weird numbers in it
so when I print it out, it it prints
35536326411 -858993460 -858993460
it prints that -858993460 to what I assume is about 200 times.
I'm a total noob in C and in programming. I asked the professor about the array size and he said just set it to a large number like 100 or 200 because trying to set the size of the array to a variable that can be changed (or something to that concept) is complicating and isn't at our level quite yet.
I need to do math with these numbers and I don't want to include those -858993460 things in my calculations. How would I determine where in the array is the last element that was actually declared?
Someone please point me into the right direction...
for (i = 0; i <= SIZE; ++i)
should be
for (i = 0; i < SIZE; ++i)
Else you have array out of bound access which will lead to undefined behavior.
for (i = 0; i < SIZE; ++i)
{
if(fscanf(ifp, "%d", &inputArray[i]) != 1)
break;
}
Set all elements to 0 using
memset(array,0,sizeof(array));
You can check the return value of fscanf() and once it returns failure [return !=1], you should stop scanning anymore.
Further, you can use that i-1 value for printing valid elements.
Also, you should change your loop limit to i < SIZE to avoid off-by-one error.
Then, you can initialize the local variables to avoid them having garbage values. You can use memeset() or initializer-lists to get that part done.
Don't define SIZE, make it a variable that will contains real count of number in file after reading.
size_t SIZE = 0;
for (SIZE = 0; ; ++SIZE)
{
if (fscanf(ifp, "%d", &inputArray[i]) == EOF)
break;
}

How to scanning lines, each line differently, in c?

Lets say i have this text file for example:
4
1 2 3 4
3 9 8 7
1 1 2 1
8 7 8 6
I want to store the first line ("4") to one variable, and the other lines,
insert them to 2d matrix as the way they showing (dynamic 2d array).
Notice that its just example, i just know that the first line is one char, and i don't know the len of the rest of the lines except that are N*N matrix.
How can i do this in C?
Edited: so the matrix should only have numbers, so sor example this txt file:
4
1 2 3 4
3 9 8 7
1 W 2 1
8 7 8 6 is illegal . how can i handle this?
#include <stdio.h>
#include <stdlib.h>
int main(void){
FILE *fp = fopen("data.txt", "r");
int n;
fscanf(fp, "%d", &n);
int (*mat)[n] = malloc(sizeof(int[n][n]));
int *p = &mat[0][0];
while(p < &mat[n-1][n])
fscanf(fp, "%d", p++);
fclose(fp);
//check
for(int r=0; r < n; ++r){
for(int c=0; c < n; ++c)
printf("%d ", mat[r][c]);
printf("\n");
}
free(mat);
return 0;
}

Resources