I need a little help with something I'm writing C.
So I have this:
int a;
int one = 4;
int two = 3;
printf("If you have done this then write '1', if you have done that write '2' ");
scanf("%d" ,&a);
if (a=1)
{
one = one+1;
}
else if (a=2)
{
two = two+1
}
So the thing I want to do is to save that increment so the next time I open the program, the values of int one and two will change based on the last usage of the program.
How do I do this ?
Use fopen/fread/fclose when you start the application (before write checks if the FILE handle is correctly created)
Use fopen/fwrite/fclose when you exit from the application.
How to access file? very basic functionalities, read this:
http://www.thegeekstuff.com/2012/07/c-file-handling/
When the program finishes processing it is removed from the memory along with it's variables. What you what to achieve requires file handling. See this tutorial - http://www.w3schools.in/c/file-handling/
A couple of suggestions:
1 - It's supposed to be if (a==1)
2 - It's always recommended to add the else block for a if..else if control block to handle any unexpected input
Read both variables from file and write it to the file before closing the program.
#include <stdio.h>
int main(void)
{
int a;
FILE *fp = fopen("save.txt", "r+"); // File contains two integers 4 3
int one;
int two;
fscanf(fp, "%d %d", &one, &two);
printf("%d %d\n", one, two);
printf("If you have done this then write '1', if you have done that write '2' ");
scanf("%d" ,&a);
if (a==1)
{
one = one+1;
}
else if (a==2)
{
two = two+1;
}
rewind(fp);
fprintf(fp,"%d %d\n", one, two);
}
Related
Write a C program that reads from the keyboard a natural number n
with up to 9 digits and creates the text file data.out containing the
number n and all its non-zero prefixes, in a single line, separated by
a space, in order decreasing in value. Example: for n = 10305 the data
file.out will contain the numbers: 10305 1030 103 10 1.
This is what I made:
#include <stdio.h>
int main()
{
int n;
FILE *fisier;
fisier=fopen("date.in","w");
printf("n= \n");
scanf("%d",&n);
fprintf(fisier,"%d",n);
while(n!=0)
{
fisier=fopen("date.in","r");
n=n/10;
fprintf(fisier,"%d",n);
}
fclose(fisier);
}
Few things:
Function calls may return error. You need to check that every time.
fisier=fopen("date.in","w");
This should have been followed by an error check. To understand more on what it return, first thing you should do is read the man page for that function. See man page for fopen(). If there is an error in opening the file, it will return NULL and errno is set to a value which indicates what error occurred.
if (NULL == fisier)
{
// Error handling code
;
}
Your next requirement is separating the numbers by a space. There isn't one. The following should do it.
fprintf(fisier, "%d ", n);
The next major problem is opening the file in a loop. Its like you are trying to open a door which is already open.
fisier=fopen("date.in","r");
if(NULL == fisier)
{
// Error handling code
;
}
while(n!=0)
{
n=n/10;
fprintf(fisier,"%d",n);
}
fclose(fisier);
A minor issue that you aren't checking is the number is not having more than 9 digits.
if(n > 999999999)
is apt after you get a number. If you want to deal with negative numbers as well, you can modify this condition the way you want.
In a nutshell, at least to start with, the program should be something similar to this:
#include <stdio.h>
// Need a buffer to read the file into it. 64 isn't a magic number.
// To print a 9 digit number followed by a white space and then a 8 digit number..
// and so on, you need little less than 64 bytes.
// I prefer keeping the memory aligned to multiples of 8.
char buffer[64];
int main(void)
{
size_t readBytes = 0;
int n = 0;
printf("\nEnter a number: ");
scanf("%d", &n);
// Open the file
FILE *pFile = fopen("date.in", "w+");
if(NULL == pFile)
{
// Prefer perror() instead of printf() for priting errors
perror("\nError: ");
return 0;
}
while(n != 0)
{
// Append to the file
fprintf(pFile, "%d ", n);
n = n / 10;
}
// Done, close the file
fclose(pFile);
printf("\nPrinting the file: ");
// Open the file
pFile = fopen("date.in", "r");
if(NULL == pFile)
{
// Prefer perror() instead of printf() for priting errors
perror("\nError: ");
return 0;
}
// Read the file
while((readBytes = fread(buffer, 1, sizeof buffer, pFile)) > 0)
{
// Preferably better way to print the contents of the file on stdout!
fwrite(buffer, 1, readBytes, stdout);
}
printf("\nExiting..\n\n");
return 0;
}
Remember: The person reading your code may not be aware of all the requirements, so comments are necessary. Secondly, I understand english to a decent level but I don't know what 'fisier' means. Its recommended to name variables in such a way that its easy to understand the purpose of the variable. For example, pFile is a pointer to a file. p in the variable immediately gives an idea that its a pointer.
Hope this helps!
To draw a conclusion from all the comments:
fopen returns a file handle when successfull and NULL otherwise. Opening a file twice might result in an error (it does on my machine), such that fisier is set to NULL inside the loop. Obvioulsy fprintf to NULL wont do anything.
You only need to call fopen once, so remove it from the loop. After that it will work as intended.
It's alwas good to check if the fopen succeeded or not:
FILE *fisier;
fisier=fopen("date.in","w");
if(!fisier) { /* handle error */ }
You print no spaces between the numbers. Maybe that's intended, but maybe
fprintf(fisier,"%d ",n);
would be better.
For input two files "cl-clean-history" and "cd-clean-history" of similar structure of:
"Lift Convergence"
"Iterations" "cl"
1 1.14094e+00
2 1.14094e+00
and
"Drag Convergence"
"Iterations" "cd"
1 0.14094e+00
2 0.14094e+00
I want to write a program to read the values in second columns in both files and compute its divisor.
My program code is:
#include <stdio.h>
#include <errno.h>
int main (void)
{
double max_cl_cd, cl_cd_temp;
int lines_file;
int tab_line;
double tab_scan_file[200000][4];
int ch=0;
FILE *result_search_cl;
FILE *result_search_cd;
max_cl_cd=0.0;
if((result_search_cl=fopen("cl-clean-history","r"))==NULL)
{
printf("Unable to open input file\n");
}
else
{
lines_file = 0;
FILE *result_search_cd = fopen("cd-clean-history", "r");
FILE *result_search_cl = fopen("cl-clean-history", "r");
while (EOF != (ch=getc(result_search_cd)))
if ('\n' == ch)
++lines_file;
printf("Number of lines in file: %d \n",lines_file);
for (tab_line=0;tab_line<=lines_file;tab_line++) {
fscanf(result_search_cd,"\n");
fscanf(result_search_cd,"\n");
fscanf(result_search_cd,"%d",&tab_scan_file[tab_line][0]);
fscanf(result_search_cd,"\t");
fscanf(result_search_cd,"%f",&tab_scan_file[tab_line][1]);
fscanf(result_search_cd,"\n");
fscanf(result_search_cl,"%d",&tab_scan_file[tab_line][2]);
fscanf(result_search_cl,"\t");
fscanf(result_search_cl,"%f",&tab_scan_file[tab_line][3]);
fscanf(result_search_cl,"\n");
cl_cd_temp=tab_scan_file[tab_line][3]/tab_scan_file[tab_line][1];
if (cl_cd_temp>max_cl_cd)
{
max_cl_cd=cl_cd_temp;
}
printf("%f %f\n",tab_scan_file[tab_line][0],tab_scan_file[tab_line][1]);
}
fclose(result_search_cd);
fclose(result_search_cl);
}
printf("%f %f\n",tab_scan_file[tab_line][0],tab_scan_file[tab_line][1]);
return 0;
}
In my opinion there is something bad in scanf lines, but I don't see what exactly is bad. The first two scans of "\n" are intented to jump two first lines in file. I know that the second option is to perform loop starting from third line (for(tab_line=3; etc.) The %d scans integer value in first column and %f scans float value in second column in both files. Unfortunately, while running in Dev C++ the process exits with return value 3221225725. I found on stackoverflow.com that this value means heap corruption. How to overcome this problem?
I think you should read the fscanf documentation again:
Anyway, fscanf accepts as a second argument a format, so something like "%d" (the one you have used some lines later). When you invoke
fscanf(result_search_cd,"\n");
"\n" is not an identifier. You should replace this line with something like
while (getc(result_search_cd) != "\n"); //Skip first line
while (getc(result_search_cd) != "\n"); //Skip second line
I am reading from a text file and the file is in the format
value1: 5
value2: 4
value3: 3
value4: 2
value5: 1
and then it repeats.
I know how to grab the data I need from one line, but I've searched everywhere and looked through various books and resources and I can't figure out a way to read from every 10 lines instead of one line.
This is what I have so far and I am aware that it has a couple mistakes and I have extra variables and it is incomplete but I am able to compile and all it does is print the first value from the file. my printf is mostly just a test to see what I'm reading from the file.
#include <stdio.h>
#include <math.h>
int main()
{
int line = 0;
int time = 0;
int switch0 = 0;
int switch1 = 0;
int switch2 = 0;
int switch3 = 0;
int pot = 0;
int temp = 0;
int light = 0;
FILE *infile = fopen("data.txt", "r");
FILE *outfile = fopen("matlab.csv", "w");
if (infile == NULL)
{
printf("Error Reading File\n");
exit(0);
}
fprintf(outfile, "Time,Switch0,Switch1,Switch2,Switch3,Potentiometer,Temperature,Light");
fscanf(infile, "time: %d\nswitch0: %d\nswitch1: %d\nswitch2: %d\nswitch3: %d\npotentiometer: %d\n temperature: %d\n light: %d\n",
&time, &switch0, &switch1, &switch2, &switch3, &pot, &temp, &light) != EOF;
printf("%d\n %d\n %d\n %d\n %d\n %d\n %d\n %d\n", time, switch0, switch1, switch2, switch3, pot, temp, light);
}
tl;dr how to read every 10 lines of text file and save into array
Thanks in advance
I know how to grab the data I need from one line
Well that's a good start. If you can read one line, you can read one line n times, right?
I've searched everywhere and looked through various books and resources and I can't figure out a way to read from every 10 lines instead of one line.
It's just more of the same. You could, for example, write a function that reads exactly one line and returns the data. Then call that function the requisite number of times.
If you really want to read all the data from n lines at once, you can do that to. Instead of your code:
fscanf(infile, "time: %d\n", &time[100]);
you can make the format string more extensive:
fscanf(infile, "time: %d\nswitch1: %d\nswitch2: %d\npotentiometer: %d\n",
&time, &switch1, &switch2, &potentiometer);
The \n is just another character to fscanf() -- you don't have to stop reading at the end of one line.
Be careful with this approach, though. It leaves you open to problems if you have a malformed file -- everything will break if one of the lines you expect happens to be missing or if one of the labels is misspelled. I think you'd be better off reading one line at a time, and reading both the label and the value, like:
fscanf(infile, "%s %d\n", &label, &value);
Then you can look at the string in label and figure out which line you're dealing with, and then store the value in the appropriate place. You'll be better able to detect and recover from errors.
Let's say I have a file name already created named "room.txt" and it contains the following:
20 10 5
Once I execute the code below, I will be asked to specify which variable to decrease its value by 1.For example: If I input "1" it will reduce the number "20" in "room.txt".However, it doesn't reduce the value.Instead, it deletes the contents of "room.txt" file.How do I make it so that it retains the values in the file when I enter my input from the program?Also, how do I reduce the values '20' '10' '5' respectively when I input '1' '2' '3' in my program?
#include<stdio.h>
char rooms[]={"rooms.txt"};
struct rooms {
int stdsuite;
int premsuite;
int deluxesuite;
};
int stdsuite;
int premsuite;
int deluxesuite;
void availablerooms ()
{
FILE*fp;
fp = fopen(rooms,"r");
fscanf(fp,"%d %d %d",&stdsuite,&premsuite,&deluxesuite);
system("cls");
system("cls");
printf("\n\n");
printf("\t\t-----------------------------------------------\n");
printf("\t\t Room Availability\n");
printf("\t\t-----------------------------------------------\n\n");
printf("--------------------------------------------------------------------------------\n\n");
printf("\t\t Standard Suite :\t%d / 20\n\n",stdsuite);
printf("\t\t Premium Suite :\t%d / 10\n\n",premsuite);
printf("\t\t Deluxe Suite :\t%d / 5\n\n",deluxesuite);
printf("--------------------------------------------------------------------------------\n\n");
fflush(stdin);
}
int main ()
{
int choice;
FILE*fp;
availablerooms();
printf("1. Standard Suite\n\n2. Premium Suite\n\n3. Deluxe Suite\n\n");
printf("Please enter the selected room value (1-3): ");
scanf("%d",&choice);
fflush(stdin);
if (choice == 1)
{
fp = fopen(rooms,"w");
stdsuite--;
}
else if (choice == 2)
{
fp = fopen(rooms,"w");
premsuite--;
}
else if (choice == 3)
{
fp = fopen(rooms,"w");
deluxesuite--;
}
else
printf("\nThe input is invalid!");
}
Any help would be greatly appreciated! :)
To accomplish what you're trying to do in standard C you must:
Open the file for reading "r".
Read its contents to your own datastructure.
Modify the data structure.
freopen the file for writing "w".†
Write back the modified data structure.
Close the file.
† This is necessary because there is no standard C way to truncate the file in "r+" mode.
availablerooms should fclose(fp) before returning. And fflush(stdout) instead of stdin.
Then, when trying to write the data back, you only fopen the file, but you don't write anything to it. There you have a major misconception of how the things work. in the 3 ifs, you decrement the relevant variables. But that are purely in-memory operations. opening the file before, doesn't change that. So, remove the three fopens and put a new one after the last if statement followed by a fprintf(fp, "%d %d %d", stdsuite, premsuite, deluxesuite); to do the actual writing. then finish with an fclose(fp) again
I'm fairly new to C. This is the first program I've written involving reading and writing to files. So far, I was able to read the file, perform the operations I need but I am having trouble with 2 things.
Whatever the file is, it omits the last line when reading. For example if the file has:
3
5
6
It will only read the 3 and 5. But if I leave an empty/blank line at the bottom it'll read all three. Any ideas as why that is?
I now need to take what I did, essentially converting volts to milliVolts, microVolts, etc. and write it back to the file. What I have been doing up until now is reading it from the file and working through the console. So essentially, I want write the last two printf statements to the file. I had some attempts at this but it wasn't working and I couldn't seem to find decent support online for this. When I tried, it would completely erase what was in the file before.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
FILE * file = fopen ("bacon.txt", "r");
float voltage = 0, voltageArray[100], voltageToMilli = 0,voltageToMicro = 0, voltageToKilo = 0, voltageToMega = 0;
int i = 1, j = 0;
fscanf (file, "%f", &voltage);
while (!feof (file)) {
printf("Line # %d\n", i);
printf ("The voltage is: %f\n", voltage);
voltageArray[j] = voltage;
fscanf (file, "%f", &voltage);
printf("The voltage in Element %d is: %f Volts",j,voltageArray[j]);
voltageToMilli = voltageArray[j] * 1000;
voltageToMicro = voltageArray[j] * 1000000;
voltageToKilo = voltageArray[j] * 0.001;
voltageToMega = voltageArray[j] *0.000001;
printf("\nThe voltage is %f Volts, which is: %f milliVolts, %f microVolts, %f kiloVolts, %f megaVolts",voltageArray[j],voltageToMilli,voltageToMicro,voltageToKilo,voltageToMega);
printf("\n\n");
i++;
j++;
}
fclose (file);
return (0);
}
Please try to keep explanations clear and simple as I am a beginner in C. Thank you!
For the first issue, the problem is that the loop logic is incorrect. On each iteration is stores the previous read data, reads the next data and then goes back to the top of the loop. The problem with this is that the next data is not stored until the next iteration. But after reading the last data item (and before storing it into the array) the feof check is always false. Refer to this question for why checking feof as a loop condition is almost always wrong.
Here is an example of how you could restructure your code to read all the items as intended:
int rval;
while ((rval = fscanf(file, "%f", &voltage)) != EOF) {
if (rval != 1) {
printf("Unexpected input\n");
exit(-1);
}
voltageArray[j] = voltage;
/* Do the rest of your processing here. */
}
problem is in the file there is nothing after the last number,
so, after reading the last number from the file, feof(file) is true.
and the while exits.
simplest fix is change it to this
while(fscanf (file, "%f", &voltage) == 1) {
and remove the other fscanf calls.
this works because that fscanf() call will return 1 when it is able
to read a number and either 0 or EOF (which is a negative number)
otherwise.