Reading information from text files, line by line - c

I want to learn how to read .txt files in C, line by line so that the information in each line can be used in loops etc. I don't have a homework exercise for this but I need to figure it out for a project to write a script for an astronomy package.
So in order to learn how to do this I created a file called list.txt with the numbers 1,2,3,4,5,6,7,8,9 each on separate lines and I want the program to sum the values on each line. I also created an output file called sum.txt and the program is supposed to sum the lines, and print the sum to the output file.
I am getting an error when I run the program and I'm not sure what the problem is as I don't fully understand this. I got this program in a book on C and tried to modify it to run it on my PC.
The reason I need to be able to do this is because I need to take information from each line in a list (each line containing one string). But I want to learn to do it with numbers first.
Here's the code:
#include<stdio.h>
int main(void)
{
int a, sum = 0;
FILE *ifp, *ofp;
ifp = fopen("list.txt", "r");
ofp = ("sum.txt", "w");
while (fscanf(ifp, "%d", &a) == 1)
{
sum += a;
fprintf(ofp, "The sum is %d. \n", sum);
fclose(ifp);
}
return 0;
}

You forgot to write fopen here:
ofp = ("sum.txt", "w");
Also, you should move the fclose (and possibly the fprintf) out of the while loop, since you only want to close the file after reading all the lines.

You need to close the input file after the loop and move the fprintf outside the loop too:
} // end of while loop
fprintf(ofp, "The sum is %d. \n", sum);
fclose(ifp);
Also don't forget to do error checking and ensure that you've opened the files before you go on and to IO on them.

Related

What do I need to do to read a file then pick a line and write it to another file (Using C)?

I've been trying to figure out how I would, read a .txt file, and pick a line of said file from random then write the result to a different .txt file
for example:
.txt
bark
run
car
take line 2 and 3 add them together and write it to Result.txt on a new line.
How would I go about doing this???
I've tried looking around for resources for fopen(), fgets(), fgetc(), fprintf(), puts(). Haven't found anything so far on reading a line that isn't the first line, my best guess:
-read file
-print line of file in memory I.E. an array
-pick a number from random I.E. rand()
-use random number to pick a array location
-write array cell to new file
-repeat twice
-make newline repeat task 4-6
-when done
-close read file
-close write file
Might be over thinking it or just don't know what the operation to get a single line anywhere in a file is.
just having a hard time rapping my head around it.
I'm not going to solve the whole exercise, but I will give you a hint on how to copy a line from one file to another.
You can use fgets and increment a counter each time you find a line break, if the line number is the one you want to copy, you simply dump the buffer obtained with fgets to the target file with fputs.
#include <stdio.h>
#include <string.h>
int main(void)
{
// I omit the fopen check for brevity
FILE *in = fopen("demo.c", "r");
FILE *out = fopen("out.txt", "w");
int ln = 1, at = 4; // copy line 4
char str[128];
while (fgets(str, sizeof str, in))
{
if (ln == at)
{
fputs(str, out);
}
if (strchr(str, '\n') && (ln++ == at))
{
break;
}
}
fclose(in);
fclose(out);
return 0;
}
Output:
int main(void)

How can I append the very first line of a .txt file using C?

I have a program where I am trying to add wind data to a .txt file, but I am facing the issue where I add data, I close the program, try to add data again, and it eliminates the rest of the data. The following is an example of the .txt file:
3
3.60000 N
4.30000 E
5.40000 S
The first line is the number of data entries and the following are each wind speed and then wind direction.
My code works fine if I just add the data once and be done with it, but not if I want to add more work to what I previously did. I know I can use append to add data to the end, but it will not update the counter at the top. I want to be able to add data and also update the counter at the top. I need the counter for other functions in the code. The following is my code for the problem:
void addWindData(FILE* outFile, int numNumbers, double windSpd[], char windDir[]){
int numItems;
printf("How many data items would you like to add? ");
scanf("%d", &numItems);
fprintf(outFile, "%d \n", numItems);
for(int i = 0; i < numItems; i++){
printf("Wind speed? ");
scanf("%lf", &windSpeed[i]);
printf("Wind direction? ");
scanf(" %c", &windDir[i]);
fprintf(outFile, "%lf %c \n", windSpd[i], windDir[i]);
}
}
I call the function as so:
fp = fopen(FILE_NAME, "w");
if(fp == NULL){
printf("File could not be found! \n");
}
else{
addWindData(fp, numNumbers, windSpd, windDir);
fclose(fp);
}
Any help I could get will be greatly appreciated. I understand that 'w' will always write, but when I use append, it starts a new count at the end and then adds the data. I just need help to figure out how to update the counter! I am very new to the C programming language and am still doing my best to learn. I am trying my best to use logic and reasoning, so it helps me to get inspiration from others! Thank you in advance!
File is open as stream, so you have 2 choices: Change chars or rewrite all file. You must know that you can change only existing chars! As fopen reference says to change chars you can use "r+" mode. This mode allow to read/write, starts from beginning and allows to rewind.
you can change fp = fopen(FILE_NAME, "w") to fp = fopen(FILE_NAME, "r+") because w mode will erase the previous text in .txt file but r+ do not because r is upgrade mode.

Write a program that creates a new data file that includes only the numbers from the first file that are greater than 60

I am writing a program that creates a new data file that will take the numbers from the first file that are greater than 60 and save them to a new file.
I have began with my code but for some reason it is not saving the numbers greater than 60. I am new to programming, still learning so any help will be very much appreciated. What am I doing wrong?
#include <stdio.h>
main()
{
int y;
FILE *DATA;
DATA = fopen("RN.txt","r");
fscanf(DATA, &y);
if (y > 60)
{
DATA = fopen("RN.txt","w");
fprintf(DATA, y, "");
}
printf("Finished saving file RN.txt \n");
return 0;
}
There are several severe problems in your code.
My suggestions are as below:
Compile your program (preferrably with -Wall, enabling all warnings). You'll be getting a bunch of errors and warnings. Fix them carefully, one-by-one.
Learn How to debug small programs?
Throw what you have into the bin and read one of the good C books. Then restart from scratch.
A few insights:
You're using fscanf() and fprintf() wrongly:
fscanf(DATA, "%d", &y);
fprintf(DATA, "%d", y);
Opening the same file with two different handles to read and write at the same time will run yourself into troubles, very quickly. Close after reading or writing, or use another file for writing
fclose(DATA);
OR
FILE *OUT = fopen("RN.out.txt", "w");
To repeat a specific process, you need a loop:
while (fscanf(DATA, "%d", &y) > 0) {
// process here
}

How to read every n lines from txt file in C

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.

How to read text file in C?

I'm trying to read a txt file containing strings of 1s and 0s and print it out in the manner below. I tried my code a couple of months ago and it worked fine in reading the text file. Now when I tried it, it outputs something really strange. Also I tried changing the directory of the file to a non-existant file but it still outputs the same thing when it should've quit the program immediately. Please help!
The content of txt file:-
10000001
01110111
01111111
01111010
01111010
01110111
Expected output:-
data_in<=24'b10000001;
#10000;
Real output:-
data_in<=24'b(some weird symbol that changes everytime I recompile);
#10000;
My code:-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[])
{
int i, j;
j = 0;
char words[50];
FILE *fp;
fp = fopen (argv[1], "r");
if (fp == NULL) {
printf ("Can't open file\n");
}
while (feof (fp) == 0) {
fscanf (fp, "%s", words);
printf ("data_in<=24'b%s\n", words);
printf ("#10000\n");
}
fclose (fp);
system ("PAUSE");
return 0;
}
The input argument is the following:-
"C:\Users\Beanz\Documents\MATLAB\football frame\frame1.txt"
Read each line one by one with getline(3) -if available- or with fgets (you'll then need a large enough line buffer, at least 256 bytes), then parse each line buffer appropriately, using sscanf (the %n might be useful, and you should test the scanned item count result of sscanf) or other functions (e.g. strtok, strtol, etc...)
Remember that 'feof()' is only set AFTER trying to read PAST the end of the file, not when at the end of the file.
So the final iteration through the loop will try to read/process data that contains trash or prior contents.
Always check the returned value from 'fscanf()' before trying to use the associated data.
strongly suggest
eliminate the call to feof() and use the fscanf() to control the loop

Resources