Reading and writing of two digit value to file in C - c

I'm writing a business application in C in which I'm keeping track of a timer by writing the value to a temporary file. The counter starts at 96, and counts backwards all the way to 0. The logic works fine, except when it switches over from 10 to 9, the 9 only overwrites the 1, so instead of 10 -> 9, the value goes 10 -> 90, causing the countdown to start back from this point. Is there a way I can have my application write the value successfully?
I'm using the following two functions to control output to the file"
fprintf(fileFd, "%d" , counter);
rewind(fileFd);
I print the value to my file, then move the access point back to the head of the file for the next entry. Any advice on how this can be done? Thanks, all.
EDIT: Thank you all for the suggestions. I tried the methods suggested below, by calling %02d to write to two place values, and for some reason that completely broke the application. The loops won't happen at all.....then when I recompile, it still won't work until I delete my temp file and create a new one. Now, when writing to the file, it tells me at the bottom (this is a UNIX system) the filename, [Incomplete last line], 1 line 2 characters. Would this make any kind of difference to specifying the number of places to write to?

fprintf(fileFd, "%02d", counter);

Check with:
fprintf(fileFd, "%02d" , counter);

write to the file taking up certain number of digits, and fill unused digit with 0.
fprintf(fileFd, "%07d", counter);
The above code will allow time values upto 7 digits.

Related

How does fscanf interact with the file it parses information from?

I am kinda new to C, have written some basic programs, but other than that I know nothing special. Currently I am writing a program that needs to get its variables from a .txt file. The .txt file is always structured like this:
X Y //1st row
a1 a2 a3 a4 aX //2nd row
Where the number of a's I am getting equals the number X.(Everything in the file is an int)
The bit in my code that confuses me is this:
fscanf(txtfile,"%d %d",&X,&Y);
int input[X];
for(int i=0; i<X; i++){
fscanf(txtfile,"%d",&input[i]);
}
Which works perfectly fine, but in my mind it shouldn't...
I thought that after getting X and Y from my .txt file, the fscanf in the loop would go through them again and I would have to find a way to bypass them, so they don't end up in my input[]. I was going to make a dummy array to store the first two ints and then transfer the other ones to the proper one, but it turned out that the dummy array worked just fine and the "proper" one ended with garbage in it. So what does actually happen? Does fscanf have some kind of pointer on the file that tells it where it stopped the last time it run? Or something completely different? I tried going through the man pages for fscanf, but i didn't find anything useful, or maybe it just went over my head.
P.S. The title may be a little bit off in regards to what I am asking, but I couldn't think of a better one.
Thanks for your time!
Does fscanf have some kind of pointer on the file that tells it where it stopped the last time it run?
Close. The FILE object that txtfile points to stores the current file position, which gets updated after each successful read (or write, if it's an output stream) operation. If you find that need to go back and re-read an earlier input item, then you'll need to reset that file position using the fseek or rewind library functions.
I/O in C is hidden behind abstractions known as streams - as far as your program is concerned, a stream is just a producer (or consumer) of bytes. Each time you successfully read from a stream you "remove" those bytes from the stream1, so you're not constantly re-reading the same data over and over again.
Logically speaking - the contents of the underlying file are not altered.

Problem using printf while copying numbers from a file to an array

I have this problem with my code. Im was copying some numbers from a file i had opened into an array using a for loop. And at the same time, i put a printf statement after the fscanf statement to see whether the value i wanted actually entered the arr. This works fine except that it puts an extra number at the end of the array when it's done. i don't understand why this happens. At first, i thought that I was using a wrong count of the number of elements in the file or that i had messed up while using malloc but those are completely fine. Can anyone pls tell what wrong. I can't share the code until a specific date cause i am a student and it would be considered cheating.
EDIT: Below is a link to a segment of what is happening in the code. THE LANGUAGE IS C. The code is meant to read the numbers 1
7
5
6
8
3
9
4
2
10
from a file a made but instead it always reads 1
7
5
6
8
3
9
4
2
10
1
EDIT: In the function declaration i meant char* file_name not int char*filename.
the image but i cant embed yet so a link
There are multiple problems in your code:
there is a syntax error in the function prototype: int char* filename should just be const char *filename.
you do not test the return value of fopen(). You will have undefined behavior if the program cannot open the file.
you do not test if fscanf() succeeds at converting the file contents as an integer. You should verify the it returns 1 and handle the error if it does not.
It is quite likely that the number of values passed to the function exceeds the number of values actually present in the file. In this case, the contents of the destination array is not changed beyond the last value read and printf outputs whatever happens to be present there.
You should post the whole program as text in your question for a more complete analysis and potential corrections.

How do I read numbers from a file and assign them to multiple arrays? - C

I have to create a program that reads a file with numbers set up like this
3 1 4 3 2 5
1 4 etc.
and set them up into multiple arrays so 3 and 1 need to be in the same space in two different arrays, but in the same slot. So both 3 and 1 should end up in slot 1, 1, 4 3 would be in slot 1, 2, and so on.
I'm trying to find some form of tutorial, but so far no luck. I'm using a structure with two integers to try to assign the each number to their respective integers but can't get it to read them as explained.
If anyone knows what I'm looking for and can tell me the actual term for it so I can have a better chance to find something or can point me to a tutorial so I can properly understand how to do it I would be very grateful.
Update: Okay so far still not getting it to work, the simplest way I can describe what I want to do, is I want to read the first number, skip the second, read the third, skip the fourth, etc. and then I’ll create a separate scan statement to read the skipped numbers.
I finally figured it out. What I was doing wrong was I created a scanf to scan each
fscanf(ifp, “%d” &thing[i][j].1);
fscanf(ifp, “%d” &thing[i][j].2);
When I should have done
fscanf(ifp, “%d%d” &thing[i][j].1, &thing[i][j].2);

How to create invisible space until a new line?

I am a beginner of C language. I was recently writing a program to print a histogram of the number of instances of a character in an input. Printing the histogram horizontally is easy, but vertically is a challenge.
Please have a look at the following code:
#include <stdio.h>
int main()
{
/*THIS IS JUST A SAMPLE OF WHAT I WANT TO ASK*/
int occurrence = 5;
int i;
for (i=0;i<occurrence;i++){
printf("\t*\n");
}
}
For an example, say any letter occurs 5 times. So I have set the occurrence to 5. And I am printing the bar in the form of asterisks. Now through this code, I am able to print an histogram containing 5 asterisks. But the thing is if I want to print other elements, like the x and y axis, the code creates a \n character. So if I write the code to print other elements, they start printing from the next line. So I figured out something else.
Now read this code:
#include <stdio.h>
int main()
{
/*THIS IS JUST A SAMPLE OF WHAT I WANT TO ASK*/
int instances = 5;
int i;
for (i=0;i<instances;i++){
printf("\t*\t\t\t\t\t\t\t\t\t");
}
}
Now what I did is depending on the size of the output screen, I created 9 tab characters so that the next asterisk moves on to the next line without printing any \n character.
Now the main question: IS THERE ANY OTHER WAY TO CREATE INVISIBLE SPACES UNTIL THE NEXT THING TO BE PRINTED MOVES ON TO THE NEXT LINE?
This question might be stupid but if there is a solution, it will be best for me.
NOTE: If there is no such method of creating blank spaces then please suggest a good way to create a vertical histogram. If someone wants an improvisation in the question, I am ready to do it.
Thanks for the help!
Outputs::
If I use the first code and I make other chart elements using printf statements, this is the output::
Now can you see that the bar made of asterisks is not aligned with the x and y axis. This happens due to the \n character.
Instead of hacking around with spaces yourself, you might want to look into a library that handles all that graphical stuff for you. For example, ncurses is a pretty decent library to do pseudo-graphical output on a console. However, "ncurses" seems to be for Unix only, but there may be other libraries for Windows.
If using a library is not an option, I'd suggest to work with a 2-dimensional character buffer (that you treat like a bitmap) instead of writing things directly to the console. It's a lot less "fiddling around". Just watch out to truncate your buffer line size to the console line size before printing, in order to avoid automatic line breaks where you don't want them.
If you do not want to use curses library, for example if you have found a printing terminal in a museum and want that your program can work on it, you have to reverse the problem.
You must print line by line if you do not use a graphic library. So your program could look like :
compute the occurence of characters
compute the maximum occurence
for each line from max occurence to 0
compute a line for every character printing a space (not reached)
for each character
if the occurence is greater than the line index put a mark at correct place in the line
print the line
That's the algo, actual coding is left as exercice for the reader :-)
You might want to think about having a two dimensional array. Start by filling it with spaces. Then replace the spaces with the character you want to print at the correct index. Using two for loops, traverse the array in order to print. Print a new line at the end of the row. Changing the order of the index changes a vertical/horizontal print. Negatives are
having to keep the whole thing in memory.
Needing multiple passes. One to set the characters and another to print.

Minix 3 TTY incoming character to int

Please refer to the following code snippet, I will be referring to the line numbers on it:
https://gist.github.com/wilbertcr/474c6a13e377dc8ce51a
As you can see on line 172-200, I created a modified version of the original back_over function, which just moves the pointer without erasing the character that's moving over.
Outside of the function in_process, and as a global variable, I created int verase, see line 1, which I use on line 82 to indicate CTRL+H has been pressed(ch == tp->tty_termios.c_cc[VERASED]).
My idea is to use this as a flag so I can catch the next character, which should be the number of spaces I need to back_over, and do that by calling back_over the number of times indicated by that next character.
The problem I am having is that I don't know how to turn that next character into its corresponding int so that I can use it on the for loop. Lines 27-38 show a failed attempt to do that, however, no matter how small the key I press(I've tried 1 and 2 and 3), it always takes me to the beginning of the line(luckily back_over doesn't go beyond a line break--see line 185).
It seems like the for loop is being executed more than the it should, which I suspect is happening because "number" is not really 1 or 2 or 3 but something else, something the for loop is interpreting as much bigger than the number I am pressing in the keyboard. I would appreciate some help on how can I turn it into an int.
It turned out it was just a matter of doing:
ch=ch-'0'

Resources