Reading data from txt file in c language - c

Prepare a file called “notes.txt” which contains students' names, visa and final grades. Later
read the names, visa and final notes in the file in a structure. General with 40% of the visa and 60% of the final
Calculate the grade. Finally, students whose general grade is 60 and above are displayed on the screen with their student name and general grade.
Print the "Gecti.txt" file, the ones below 60 with the student name and general grade on the screen and the "kaldi.txt" file.
When the program runs, sample file contents and screenshot will be as follows. For the "notes.txt" file
You can use the following data, "Gecti.txt" and "Kaldi.txt" files should be created automatically when the program is run. This is what i want to do. But I dont know read a data from txt file.
In notes.txt:
Ali 50 40
Ayse 20 90
Omer 70 80
Elif 50 50
Ahmet 50 80
but I don't know how can read name and visa and final in txt file and I can't write code .pls help me
#include <stdio.h>
struct ogrenci
{
char isim[30];
int vize;
int final;
}ogr[10];
int main()
{
FILE * notlar = fopen("notlar.txt","r");
}
ı can write just this

In order to achieve this, there are the following things you need to do:
Open the file for reading (this part you have done)
Start a loop (until end-of-file is reached), and inside that loop:
Read a line from the file
Format the line (using the space character as a separator) in order to find the three different kinds of information.
Add the mentioned information in the structure you have created.
Put the mentioned structure in a collection.
Close the file
About how to read files and how to format strings, containing separators, there are plenty of examples to be found on the internet and on this site.

Related

C File Save and Restore input information

I have a program based on a struct with different information.
In this program you can for example add people and delete people etc. I already have all this done, so the program it self is done. But the files are not.
So I am trying to write a code that "saves" if I would for example add a person and this would "save" when I choose to exit the program. And a code that "restores" the people in the file in the beginning of the program.
Does any one have any ideas or tips? I'm new to programming and trying to learn. I have been sitting with this for a few days.
Before I "restore" I ask for an file to open and if this file does not exist a new one is created and this works. So if I would have a file with 3 employees and I would open this file I would want to restore them and then being able to add more employees to the file etc.
You have to write (and to read) in two steps: first the struct, and then the array the struct points to.
Code fragment for writing (a.o. without error checking, that is however needed):
#include <stdio.h>
// ...
employees emp;
const char* filename="your_filename";
// populate emp;
FILE* file = fopen(filename,"w");
fwrite(&emp,sizeof(employees),1,file);
fwrite(emp.pic,sizeof(int),emp.imageCount,file);
fclose(file);
Now you have the array after the struct in your file. Read it in the same way:
FILE* file = fopen(filename,"r");
fread(&emp,sizeof(employees),1,file);
emp.pic=calloc(sizeof(int), emp.imageCount);
fread(emp.pic,sizeof(int),emp.imageCount,file);
Please don't forget to check for errors (see man fopen|fread|fwrite|calloc). In case you have several structs, you must repeat the two steps for any element.
What is the platform? For Windows there is simple format of .INI files with contents like:
[Employee_1]
id=123
name=Smith
imageCount=2
...
You can use GetPrivateProfileString/GetPrivateProfileInt and WritePrivateProfileString API functions to read and store the information. Use separate section for each employee. One common section is necessary to store the number of employee sections.

C Programming - Scanning information from text file for use in Program

I have been a longtime viewer of Stack Overflow, but this is my first question. As such, please forgive and correct me if I am missing any important details or information!
I am just beginning to program in C. I'm trying to create a program that will take in a text file I specify via my console on run time and using stdin. This text will will be formatted in the following way:
10 2 2012
3 765 821 764
5 856 976 847 757 789
4 838 842 832 815
4 809 815 789 765
The first 3 numbers are the month, day, and year. After that the following lines contain data. The first number on each line represents the amount of data readings following it. I need to perform calculations based on the numbers following the first number after each line. So far I have been using the scanf function to obtain the data for the date and print it out as a heading.
#include <stdio.h>
int main()
{
// Define Variables
int month;
int day;
int year;
// Scan text file for month, day and year
scanf("%d", &month);
scanf("%d", &day);
scanf("%d", &year);
// Print out date and headers
printf("\nTest date: %d/%d/%d", month, day, year);
printf("\nLED Lumens\n");
return 0;
}
I need to be able to take the numbers following the first number in each line. I will then use these numbers to calculate various things (which I don't need help with). My question is what's the best way to do this? My idea would be to use scanf to get the first number in the row, then loop until the number of values in the line is reached, scanning the number each time.
So, if I scan the first number and it's a 3, I will loop and scan the next 3 numbers. I will then perform the calculations for those numbers, then repeat for each line.
Is this the right way to go about this, and will this work? Mainly I'm wondering how scanning the data from the text works. Every time I use the scanf function does it just obtain the next number in my text file. Does it work regardless that my data is on the following line?
Also note that I have not learned any of the advanced functions for dealing with text files. Hence, I am sticking to scanf to obtain the data.
Thanks! Let me know if I need any more details or clarification.
Update
Thanks to everyone who responded. I appreciate explaining how the scanf worked in the text file. I was able to get my program working. As for everyone who also responded with different functions and methods I could use, thanks! I will be sure to try those out at some point. I realize that there are probably easier and better ways to go about my task than the scanf function.
The algo you describe should work ... provided the input file is correctly formatted and you test the result of the different scanf to stop on end of file (return value <= 0).
To have something more robust, you should follow chux's advice and :
- first read full lines with fgets
- then use sscanf the way you describe, but at least you are sure to be correctly line synchronized and able to detect a missing number in input file.
scanf and friends are too complicated for your simple task.
I'd use fgets to read the lines of the file into a buffer.
Then use strtoul to obtain the numbers from within. Its second parameter can be used to find the end position of each number.
The blanks between the numbers are skipped by strtoul without problems.
Here, you will need a file pointer to work with files.
FILE* fp;
int temp;
//then open the file you want to edit
//fopen(fp,"location of file with file name","mode of opening")
fp = fopen("Home/info.txt","a");
//now read through the file
fscanf(fp,"%i",&temp);
To have a better understanding on file handling you can have look at on this tutorials:
Go4Expert: File handling
StackOverflow: file handling

How to write in file at specific location? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 8 years ago.
Improve this question
I have a homework assignment and we must use .txt files.
Here's my file example:
1 John 1234 558
2 Myke 2222 9876
...
I want to overwrite the 558 number in the file. The ID (1,2...) are given. I've been searching around and the fopen() function only provides arguments for beginning and appending.
You can use the fopen("filename", "r+b") to open a file for updating (in binary mode).
You can then use fseek to set were you want to write next and use fwrite/fputs or similar to update the data.
For example, say you start with a file test.text which looks like this
0123456789abcde
0123456789abcde
0123456789abcde
you can use the following program
#include <stdio.h>
int main(int argc, char **argv)
{
FILE *f;
if(!(f = fopen("./test.text", "r+b"))) //open the file for updating
return -1;
fseek(f, 16, SEEK_SET);//set the stream pointer 16 bytes from the start.
const char message[] = "Hello, World!";
fputs(message,f);
return 0;
}
and the result would be
0123456789abcde
Hello, World!de
0123456789abcde
you will still need to first search the file for the id you want to replace, and you may run into problems when you want to replace "558" with "12345" unless there are extra spaces on the line to pad the output. As you will start overwriting data from the next line.
fopen to open the file, then seek to the right bit, then write the appropriate bits, taking great care not to overwrite anything further in the file you didn't want to overwrite!
If you need to insert more data than was taken up by the existing text then you'll have to re-append the rest of the file contents from that point.
It is usually easier to re-write the file in its entirety. You must have a reading and a writing function already. So you read, the modify your in-memory data structures, then you write everything out again.
There are functions to seek to a given position in a file, but this position is a byte offset in the file. You do not know the offset in advance, so you will need to read the file line per line until you discover the line with the given ID. Then you can skip the name, the first number and you are at the 558. The problem now is that you can overwrite the 558 in the file, but you cannot write 12 and delete the 8 from 558. You also cannot replace the 558 with a 1234 because you would overwrite the 558 with 123 and would need to insert the 4.
One simple solution would be to work with a second file. You could read file 1 line per line and copy each line to file 2. Despite the line with the given ID. You would modify that line before writing it to file 2.
If you know how to do it, you could also work with a big buffer and do the replacement in file 1 without the need for a second file.
If you are allowed to work with two files, you should do that. If the files are short and you are allowed to read the complete file into memory, you could read the file, do the modification in memory and write back the file.
(Assuming your .txt file consists of the above mentioned 4 fields) You can have two FILE pointers one with read permissions and the other with write permission. Suppose your file is named xyz.txt, let fp_read with read access point to it, where let fp_write point to a new file xyz_bkp.txt.
Variables:
char *curr_line, *name;
int id, second_num, third_num;
The trick here is to read the file xyz.txt line by line into a string(say curr_line)
Then read the values in the line into different variables using sscanf. Eg-
sscanf(curr_line, "%d %s %d %d", &id, name, &second_num, &third_num);
Now based on values of the variables, either write the values to the xyz_bkp.txt file unconditionally or change them as per your will.
NOTE: After you are done, you would need to delete the original xyz.txt and rename xyz_bkp.txt to xyz.txt(simple enough)

Appending text information to a text file at a certain spot without overwriting old information (C)

So I have a txt file that looks like this:
112 12.50 Y 15
267 7.75 N 20
382 15.50 N 45
User is prompted where he wants to insert a new ID. My job is to make the program write the new ID into the .txt file without totally overwriting all the information. Say the user wanted to insert the new ID after 267. The user tells me new ID is 123, 12.34, N, 12. The .txt file would have to look like this:
112 12.50 Y 15
267 7.75 N 20
123 12.34 N 12
382 15.50 N 45
In standard C there's no functionality to insert new data at a certain location within a file.
The only two options in plain C are:
Create a temporary file, copy the old file's data up to the insertion point to the temp file, write the new data to the temp file, copy the rest of the old file's data to the temp file, rename the temp file to the old file's name.
Figure out how much new data needs to be inserted, move (by copying) all data from the insertion point by that amount, write the new data at the insertion point.
There may be OS-specific functions to perform insertion of data at an arbitrary location within a file. But, again, not in the standard C library as defined by the C standard.
The only option that you have to add information in the middle of a file without overwriting old data is to move manually all the data following the position where you want to add into the file.
steps:
Create a temporary file
Read each line from the source file and write to temporary file, parsing it as you go
Then insert the new line after you've found the ID after which you would want the new line to be inserted
write all the remaining lines from the source file
delete the source file
rename the temporary file to the name of the source file.
celebrate!

Read/Write files in C

I'm writing a program in C that basically creates an archive file for a given list of file names. This is pretty similar to the ar command in linux. This is how the archive file would look like:
!<arch>
file1.txt/ 1350248044 45503 13036 100660 28 `
hello
this is sample file 1
file2.txt/ 1350512270 45503 13036 100660 72 `
hello
this is sample file 2
this file is a little larger than file1.txt
But I'm having difficulties trying to exract a file from the archive. Let's say the user wants to extract file1.txt. The idea is it should get the index/location of the file name (in this case file1.txt), skip 58 characters to reach the content of the file, read the content, and write it to a new file. So here's my questions:
1) How can I get the index/location of the file name in the archive file? Note that duplicate file names are NOT allowed, so I don't have to worry about having two different indecies.
2) How can I skip several characters (in this case 58) when reading a file?
3) How can I figure out when the content of a file ends? i.e. I need it to read the content and stop right before the file2.txt/ header.
My approach to solving this problem would be:
To have a header information that contains the size of each file, its name and its location in the file.
Then parse the header, use fseek() and ftell() as well as fgetc() or fread() functions to get bytes of the file and then, create+write that data to it. This is the simplest way I can think of.
http://en.wikipedia.org/wiki/Ar_(Unix)#File_header <- Header of ar archives.
EXAMPLE:
#programmer93 Consider your header is 80 bytes long(header contains the meta-data of the archive file). You have two files one of 112 bytes and the other of 182 bytes. Now they're laid out in a flat file(the archive file). So it would be 80(header).112(file1.txt).182(file2.txt).EOF . Thus if you know the size of each file, you can easily navigate(using fseek()) to a particular file and extract only that file. [to extract file2.txt I will just fseek(FILE*,(112+80),SEEK_SET); and then fgetc() 182 times. I think I made myself clear?
If the format of the file cannot be changed by adding additional header information to help, you'll have to search through it and work things out as you go.
This should not be too hard. Just read the file, and when you read a header line such as
file1.txt/ 1350248044 45503 13036 100660 28 `
you can check the filename and size etc. (You know you'll have a header line at the start after the !<arch>). If this is the file you want, the ftell() function from stdio.h will tell you exactly where you are in the file. Since the file size in bytes is given in the header line, you can read the file by reading that particular number of bytes ahead in the normal manner. Similarly, if it is not the file you want, you can use fseek() to move forward the number of bytes in the file you are skipping and be ready to read in the header info for the next file and repeat the process.

Resources