Output Text from File in Reverse Order in C - c

I was trying to make a code on C, which reads the file.txt, outputs it into console, and then counts rows, words etc, and after all is exporting the content of file.txt to file2.txt but in reverse order.
The text need to go from this:
I
Love
You
to this:
ouY
evoL
I
What I have in my text.file:
enter image description here
What i get with my code now:
enter image description here
Here is my code that's need improvement, because it prints the code how i need but with blank rows, which is not needed. And it needs to be exporting into another file also:
fseek(fptr,0,SEEK_END);
pos=ftell(fptr);
i=0;
while(i<pos)
{
i++;
fseek(fptr,-i,SEEK_END);
ch=fgetc(fptr);
printf("%c",ch);
}
there's full code:
#include <stdio.h>
int main ()
{
FILE *fptr;
int i, n, j, pos;
char str[100];
char fname[20]="mfile.txt";
char newch[500];
int wrd=1,charctr=1,rows=1;
char str1;
char ch;
int no_lines = 1;
int COUNT = 0;
fptr = fopen(fname,"r");
if(fptr == NULL)
{
printf(" \n");
printf("File does not exist or can not be opened.");
}
else
{
ch=fgetc(fptr);
printf(" \n");
printf("The content of the file %s are: \n", fname);
printf(" \n");
while(ch != EOF)
{
printf("%c",ch);
if(ch==' '||ch=='\n')
{
wrd++;
}
else
{
charctr++;
}
if(ch=='\n')
{
rows++;
}
ch=fgetc(fptr);
}
int wrd1 = wrd - 1;
float charctr1 = charctr - 1;
float rows1 = rows;
float averageSymbol = charctr1 / rows1;
printf(" \n");
printf("\nwrd = %d, charctr = %d", wrd, charctr-1);
printf("\nThe number of rows in the file %s are : %d\n", fname,rows);
printf("\nThe average amount of symbols in a row is %f\n", averageSymbol);
printf(" \n");
}
fseek(fptr,0,SEEK_END);
pos=ftell(fptr);
i=0;
while(i<pos)
{
i++;
fseek(fptr,-i,SEEK_END);
ch=fgetc(fptr);
printf("%c",ch);
}
fclose(fptr);
return 0;
}

Ok so if I understand correctly you want to get rid of some of the empty lines which show up in your code and then you want to also write the output of the program (the reversed text) into another file? I am assuming that you want the sentences to be also in the original order.
#include <stdio.h>
int main ()
{
FILE *fptr;
FILE *fptr2;
int i, n, j, pos;
char str[100];
char fname[20]="mfile.txt";
char fname2[20]="outputfile.txt";
char newch[500];
int wrd=1,charctr=1,rows=1;
char str1;
char ch;
int no_lines = 1;
int COUNT = 0;
fptr2 = fopen(fname2, "w+");
fptr = fopen(fname,"r");
if(fptr == NULL)
{
printf(" \n");
printf("File does not exist or can not be opened.");
}
else
{
ch=fgetc(fptr);
printf("The content of the file %s are: \n", fname);
while(ch != EOF)
{
printf("%c",ch);
if(ch==' '||ch=='\n')
{
wrd++;
}
else
{
charctr++;
}
if(ch=='\n')
{
rows++;
}
ch=fgetc(fptr);
}
int wrd1 = wrd - 1;
float charctr1 = charctr - 1;
float rows1 = rows;
float averageSymbol = charctr1 / rows1;
printf("\nwrd = %d, charctr = %d", wrd, charctr-1);
printf("\nThe number of rows in the file %s are : %d\n", fname,rows);
printf("The average amount of symbols in a row is %f\n", averageSymbol);
}
fseek(fptr,0,SEEK_END);
pos=ftell(fptr);
i=0;
while(i<pos)
{
i++;
fseek(fptr,-i,SEEK_END);
ch=fgetc(fptr);
printf("%c",ch);
fputc(ch,fptr2);
}
fclose(fptr);
fclose(fptr2);
return 0;
}
This version first checks if a file called outputfile.txt exists and if no, it creates it. If said file already exists then the program overwrites the stuff which was originally in the file with the new program output (it doesn't clear the file all the way).

Related

Selectively reading string part of a file using C

I have a .txt file with strings each line and a number assigned to each string and a - in between the string and the number.
Now I want to read only the string part not the number or the - in between, store them in an array and write only the strings in another file.
I used the following approach:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
struct String {
long long int num;
char name[50];
char C;
} S[MAX], temp;
void file_write(int n, struct String S[]) {
FILE *pp;
pp = fopen("std3.txt", "a"); //second file where I want to write only string part.
for (int i = 0; i < n; i++) {
fprintf(pp, "%s", S[i].name); //storing the strings in another file
fputs("\n", pp);
}
fclose(pp);
}
int main() {
int n;
FILE *fp;
fp = fopen("str.txt", "r");
printf("Enter the number of strings : ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
fscanf(fp, " %[^\n]", S[i].name);
fscanf(fp, "%lld", &S[i].num);
fscanf(fp, "%c", &S[i].C);
}
file_write(n, S);
fclose(fp);
return 0;
}
But I'm getting an undesirable output:
Here is a simple solution using fscanf() and the * assignment suppression option:
#include <stdio.h>
int main() {
int n = 0;
FILE *fp = fopen("str.txt", "r");
// second file where I want to write only string part.
FILE *pp = fopen("std3.txt", "a");
if (fp == NULL || pp == NULL) {
fprintf(stderr, "cannot open files\n");
return 1;
}
printf("Enter the number of strings: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
char name[50];
int c;
if (fscanf(fp, "%*d - %49[^\n]", name) == 1) {
fprintf(pp, "%s\n", name);
/* flush any extra characters and the newline if present */
while ((c = getc(fp)) != EOF && c != '\n')
continue;
} else {
break;
}
}
fclose(fp);
fclose(pp);
return 0;
}
Scanf (and its variations) is a very powerful function... I think the following line is what you want.
for(int i=0;i<n;i++)
{
fscanf(fp, "%*[^A-Z]%[^\n]", S[i].name);
}
A brief description of what it does is: It discards any character that is not a capital letter then reads everything from the first capital letter until the end of line.
If the names are allowed to start with lowercase, you can change it to:
fscanf(fp, "%*[^A-Za-z]%[^\n]", S[i].name);

C Problems with fscanf

Thanks for all the answers, after the corrections the code did not work for a stupid error ... I opened both files with the same file pointer "database" ...
I've read dozens of questions like this but I can't get out of it, I'm going crazy.
The exercise that I have to do asks me to organize the items of a list in a file .txt that has elements of the type: Name Surname Age Wage, in alphabetical order according to the surname.
I have already created a function to insert the elements into the file and it works well.
I then went to the function to organize them but the process stops after the fscanf, and putting some test printf I saw that no values are assigned to the strings or that are assigned absurd numbers.
Please help ... thanks.
This is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX 64
#define MAXFILE 100
void insert();
int fullcheck();
void sort();
typedef struct {
char name[MAX];
char surname[MAX];
int age;
double wage;
} data;
int main() {
insert();
return EXIT_SUCCESS;
}
void insert() {
char c;
int i;
data tmp;
FILE* database;
if ((fullcheck())>MAXFILE-1)
printf("Errore: database pieno.\n");
else {
database=fopen("database.txt", "a");
printf("Nome: ");
fgets(tmp.name, MAX, stdin);
tmp.name[strlen(tmp.name)-1]='\0';
printf("Cognome: ");
fgets(tmp.surname, MAX, stdin);
tmp.surname[strlen(tmp.surname)-1]='\0';
for (i=0; i<strlen(tmp.surname); i++) {
if (tmp.surname[i]==' ')
tmp.surname[i]='#';
}
printf("Eta': ");
scanf("%d", &tmp.age);
printf("Salario: ");
scanf("%lf", &tmp.wage);
while((c=getchar())!='\n');
fprintf(database, "%s %s %d %.0lf \n", tmp.name, tmp.surname, tmp.age, tmp.wage);
fflush(database); fclose(database);
if ((fullcheck())>1)
sort();
}
}
int fullcheck() {
char c;
int r=0;
FILE* database;
if ((database=fopen("database.txt", "r"))==NULL) {
return 0;
}
else {
while((c=getc(database))!=EOF) {
if(c=='\n')
r++;
}
return r;
}
}
void sort() {
char tmpstr[MAX];
int len=fullcheck(), i, a, b;
data tmp[len];
FILE* database;
FILE* sorted;
database=fopen("database.txt", "r");
database=fopen("sorted.txt", "w");
for (i=0; i<=len; i++) {
fscanf(database, "%s %s %d %lf \n", &tmp[i].name, &tmp[i].surname, &tmp[i].age, &tmp[i].wage);
}
for (a=0 ; a<(len-1); a++) {
for (b=0; b<(len-1); b++) {
if ((tolower(tmp[b].surname[0]))>(tolower(tmp[b+1].surname[0]))) {
strcpy(tmpstr, tmp[b].surname);
strcpy(tmp[b].surname, tmp[b+1].surname);
strcpy(tmp[b+1].surname, tmpstr);
}
}
}
for (a=0; a<(len-1); a++) {
fprintf(sorted, "%s %s %d %.0lf \n", tmp[a].name, tmp[a].surname, tmp[a].age, tmp[a].wage);
}
fflush(database); fclose(database); remove("database.txt");
fflush(sorted); fclose(sorted); rename("sorted.txt", "database.txt");
}
Off by 1
Code attempts to read into len+1 elements of tmp[].
data tmp[len];
for (i=0; i<=len; i++) { // too many
fscanf(database, "%s %s %d %lf \n", &tmp[i].name, &tmp[i].surname, &tmp[i].age, &tmp[i].wage);
}
I saw that no values are assigned to the strings (OP)
Better code would use width limits and test fscanf() result before using the data scanned.
// v---- < not <=
for (i=0; i<len; i++) {
if (fscanf(database, "%63s %63s %d %lf",
&tmp[i].name, &tmp[i].surname, &tmp[i].age, &tmp[i].wage) != 4) {
// ^^^^ test!
break;
}
Even better code would read a line with fgets() into a stirng and then attempt to parse the string.
Off by 2
Code's attempt to find number of lines can be short by 1 if the last line does not end with a '\n'.
Alternative
size_t fullcheck(void) {
FILE* database = fopen("database.txt", "r");
if (database == NULL) {
return 0;
}
int previous = '\n';
int c;
size_t r=0;
while((c=getc(database))!=EOF) {
if (previous == '\n') r++;
previous = c;
}
fclose(database);
return r;
}
Missing fclose()
fullcheck() doesn't close the file after opening it.
int
Use an int to distinguish the typically 257 different returns values of fgetc(). Note when char` is unsinged, OP's code is an infinite loop.
More woes
The loop to print the sorted list is off-by-one, too short. And the sorting itself only looks at the first letter of each name, should use strcmp.
#user3386109
Maybe more?
Make sure to close the file here, before every return:
int fullcheck() {
char c;
int r=0;
FILE* database;
if ((database=fopen("database.txt", "r"))==NULL) {
fclose(database);
return 0;
}
else {
while((c=getc(database))!=EOF) {
if(c=='\n')
r++;
}
fclose(database);
return r;
}
}
And also a little bit fixing in the loop_counters here:
void sort() {
char tmpstr[MAX];
int len=fullcheck(), i, a, b;
data tmp[len];
FILE* database;
FILE* sorted;
database=fopen("database.txt", "r");
sorted=fopen("sorted.txt", "w+");
for (i=0; i<len; i++) {
fscanf(database, "%s %s %d %lf \n", &tmp[i].name, &tmp[i].surname, &tmp[i].age, &tmp[i].wage);
printf("%s", tmp[b+1].surname);
system("pause");
}
for (a=0 ; a<(len); a++) {
for (b=0; b<(len); b++) {
if ((tolower(tmp[b].surname[0]))>(tolower(tmp[b+1].surname[0]))) {
strcpy(tmpstr, tmp[b].surname);
strcpy(tmp[b].surname, tmp[b+1].surname);
strcpy(tmp[b+1].surname, tmpstr);
printf("%s", tmp[b+1].surname);
system("pause");
}
}
}
for (a=0; a<(len); a++) {
fprintf(sorted, "%s %s %d %.0lf \n", tmp[a].name, tmp[a].surname, tmp[a].age, tmp[a].wage);
}
fclose(sorted);
fclose(database);
}

fscanf not reading from a file containing asterisk characters

I tried to read a file containing an empty box of '*', the error message doesn't get printed, so the file is opened, but the scan doesn't work. I tried to print the count variable, and the value of count is 0. I don't really know where the fault is. Please help... Thanks
the file content that I want to read
int openmap(int file_no){
char filename[32];
char mapp[100][100];
int number;
int count;
int x[100];
int nomor = 1;
for(int i = 1; i <= file_no; i++){
sprintf(filename, "map%d.txt", i);
FILE *test = fopen(filename,"r");
if(test)
{
printf("%2d. Map %d\n", nomor, i);
x[nomor-1] = i;
nomor++;
fclose(test);
}else if(!test && i > file_no){
printf("No map available!");
return 1;
}
}
do{
printf("[0 to cancel] [1 - %d]>> ", nomor-1);
scanf("%d", &number);
}while(number < 0 || number > file_no);
if(number > 0){
sprintf(filename,"map%d.txt", x[number-1]);
printf("%s", filename);
FILE *open = fopen(filename, "r");
if(!open){
printf("error");
}
while(!feof){
fscanf(open, "%[^\n]\n", mapp[count]);
count++;
}
fclose(open);
for(int i = 0; i < count ; i++){
printf("%s\n", mapp[i]);
}
}
}
I created a small test program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main () {
char mapp[100][100];
int i, count = 0;
char filename[32];
sprintf(filename, "test.txt");
FILE *open = fopen(filename, "r");
if(!open){
printf("error");
}
while(!feof(open)){
fscanf(open, "%[^\n]\n", mapp[count]);
count++;
}
fclose(open);
for(i = 0; i < count ; i++){
printf("%s\n", mapp[i]);
}
}
as far as i can see the only issue you have regarding the relevant section is your while loop condition, you should use: while(!feof(open)) - i tested my solution and it works so it seems that this is the only issue in your solution

searching data from dat file using c

The following program creates a new dat file and stores random data. Then one of the values is searched from the file and printed.
The problem is data up to 13 items are searched and the program exits. As shown in following picture 100 inputs are stored and only 13 items are searched. What is the solution?
// database for storing random values in file and making search operation
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
int rollNo;
int regdNo;
int salary;
int status;
} record;
int main(void) {
int i, n;
record det;
int recordsize = sizeof(det); // size of record
FILE *fp1 = fopen("random.dat", "a+");
if (fp1 == NULL) {
printf("error in opening file : \n");
return 1;
}
printf("enter the no of data to be stored\n");
scanf("%d", &n);
for (i = 0; i < n; i++) {
det.rollNo = rand();
det.regdNo = rand();
det.salary = rand();
det.status = (rand() % 10) + 1;
fwrite(&det, recordsize, 1, fp1);
}
printf("The last roll no of student stored in list: %d\n", det.rollNo);
int stat = 0, countNumber = 0;
record buffer;
int number;
printf("enter the roll number to be searched\n");
scanf("%d", &number);
fseek(fp1, 0, SEEK_SET); // move file position indicator to beginning of file
do {
countNumber++; // counts number of times the file is searched
fread(&buffer, recordsize, 1, fp1);
if (buffer.rollNo == number) {
stat = 1;
break;
}
} while (!feof(fp1));
printf("\n");
if (stat) {
printf("succesfully found at %d\n", countNumber);
printf(" roll number %d\n regd number %d\n salary %d\n status %d\n",
buffer.rollNo, buffer.regdNo, buffer.salary, buffer.status);
} else
printf("there is no such roll number %d in the list\nlength of list : %d\n",
number, countNumber);
fclose(fp1);
}
The output is:
The code works fine on my system, but there are possible problems:
you open the binary file in default mode, possibly text mode. Use "ab+" instead.
the file is open in append mode. If it contains invalid data, especially if its size is not a multiple of the size of the record size, appended records will not be properly aligned, and thus will not be read back correctly.
test the success of the scanf(), fwrite() and fread() calls
the end of file test is incorrect.
Here is an improved version:
// database for storing random values in file and making search operation
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
int rollNo;
int regdNo;
int salary;
int status;
} record;
int main(void) {
int i, n;
record det;
int recordsize = sizeof(det); // size of record
FILE *fp1 = fopen("random.dat", "ab+");
if (fp1 == NULL) {
printf("error in opening file : \n");
return 1;
}
printf("enter the no of data to be stored\n");
if (scanf("%d", &n) != 1)
return 1;
for (i = 0; i < n; i++) {
det.rollNo = rand();
det.regdNo = rand();
det.salary = rand();
det.status = (rand() % 10) + 1;
if (fwrite(&det, recordsize, 1, fp1) != 1) {
perror("cannot write record");
fclose(fp1);
return 2;
}
}
printf("The last roll no of student stored in list: %d\n", det.rollNo);
int stat = 0, countNumber = 0;
record buffer;
int number;
printf("enter the roll number to be searched\n");
if (scanf("%d", &number) != 1)
return 1;
fseek(fp1, 0, SEEK_SET); // move file position indicator to beginning of file
while (fread(&buffer, recordsize, 1, fp1) == 1) {
countNumber++; // counts number of times the file is searched
if (buffer.rollNo == number) {
stat = 1;
break;
}
}
printf("\n");
if (stat) {
printf("successfully found at %d\n", countNumber);
printf(" roll number %d\n"
" regd number %d\n"
" salary %d\n"
" status %d\n",
buffer.rollNo, buffer.regdNo, buffer.salary, buffer.status);
} else {
printf("there is no such roll number %d in the list\n"
"length of list : %d\n",
number, countNumber);
}
fclose(fp1);
return 0;
}
Your main problem is that your store binary data where system expect you to store text, see this question.
fopen(..., "a+"); open a file for text reading, but you store binary data in it
You have some other issues:
You don't use feof the right way
Your main function does not return value,
You do not test the value of n or number.
Corrected code should looks like:
// database for storing random values in file and making search operation
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct
{
int rollNo;
int regdNo;
int salary;
int status;
} record;
int main(void) {
int i, n;
record det;
/* open the file in BINARY mode */
FILE* fp1 = fopen("random.dat" , "a+b");
if (fp1 == NULL) {
printf("error in opening file : \n");
return 1;
}
printf("enter the no of data to be stored\n");
scanf("%d", &n);
for (i = 0; i < n; i++) {
det.rollNo = rand();
det.regdNo = rand();
det.salary = rand();
det.status = (rand() % 10) + 1;
if (1 != fwrite(&det, sizeof det, 1, fp1)) {
perror("fwrite");
return 2;
}
}
printf("The last roll no of student stored in list: %d\n", det.rollNo);
int stat = 0, countNumber = 0;
record buffer;
int number;
printf("enter the roll number to be searched\n");
scanf("%d", &number);
fseek(fp1, 0, SEEK_SET); // rewind would have done the job
while (1) {
countNumber++; // counts number of times the file is searched
if (1 != fread(&buffer, sizeof buffer, 1, fp1)) {
perror("fread");
return 3;
}
if (buffer.rollNo == number) {
stat = 1;
break;
}
}
printf("\n");
if (stat) {
printf("succesfully found at %d\n", countNumber);
printf(" roll number %d\n regd number %d\n salary %d\n status %d\n", buffer.rollNo, buffer.regdNo, buffer.salary, buffer.status);
}
else
printf("there is no such roll number %d in the list\nlength of list : %d\n", number, countNumber);
/* warning: file is not closed in case of error... */
fclose(fp1);
return 0;
}

Creating a program in C that saves and shows data

I'm new with C, and on the university they are making us create a program that can save data introduced by the user, read the data and check if it’s well introduced. After that it must save that data in each free space, you have 10 empty spaces for saving the data. With all the data saved it must show also the data and compare it with all the data introduced. I made the part of reading the data introduced and cheking if its ok. The problem that I have is that I don’t know how I could make the data base and show that data. Here is the code that I have till now.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char name[30];
int num_sample;
char section;
int cabin;
int day;
int month;
int year;
}Species;
int menu() {
int op = 0;
printf ("\nPrototype Nature Reserve.\n");
printf ("1. Insert a new species.\n");
printf ("2. List the species housed.\n");
printf ("3. Show stadistics.\n");
printf ("4. Exit.\n");
printf ("\nIntroduce an option: ");
scanf ("%d", &op);
return op;
}
void New_species() {
Species e;
int i, j;
char species[100];
char aux[10];
printf("Enter data:\n");
//A fflush is made to not have a problem with the number entered in the menu
fflush(stdin);
gets (species);
//While it is different from - read the text
for (i = 0; species[i] != '-'; i++) {
e.name[i] = species[i];
}
e.name[i] = '\0';
i++;
//We add 1 to the position i because is ending in - and should start reading from the following
for (j = 0; species[i] != '-'; i++,j++) {
aux[j] = species[i];
}
aux[j] = '\0';
e.num_sample = My_atoi(aux);
// Check that the sample is a number and not a character
if (e.num_sample <= 0 || e.num_sample >= 100) {
printf ("--> Error in data format.\n");
}
i++;
//Reads the day introduced
for (j = 0; species[i] != '/'; i++, j++) {
aux[j] = species[i];
}
aux[j] = '\0';
e.day = My_atoi(aux);
//Controls the format of the day
if (e.day <= 0 || e.day > 31) {
printf ("--> Error in data format.\n");
}
i++;
//Reads the month introduced
for (j = 0; species[i] != '/'; i++, j++) {
aux[j] = species[i];
}
aux[j] = '\0';
e.month = My_atoi(aux);
//Controls the format of the month
if (e.month <= 0 || e.month > 12) {
printf ("--> Error in data format.\n");
}
i++;
//Reads the year introduced
for (j = 0; species[i] != '-'; i++, j++) {
aux[j] = species[i];
}
aux[j] = '\0';
e.year = My_atoi(aux);
//Controls the format of the year
if (e.year < 1970 || e.year > 2060) {
printf ("--> Error in data format.\n");
}
i++;
//Reads the section introduced
e.section = species[i];
//Controls that the section is in capital letters
if (e.section < 'A' || e.section > 'Z') {
printf ("--> Error in data format.\n");
}
i+= 2;
//As the cabin is at the end it must reach the \0
for (j = 0; species[i] != '\0'; i++, j++) {
aux[j] = species[i];
}
aux[j] = '\0';
e.cabin = My_atoi(aux);
if (e.cabin < 0 || e.cabin > 20) {
printf ("--> Error in data format.\n");
}
printf ("Species stored successfully (%d/10 free).");
//This printf is just to ensure that the data entered was read correctly
printf ("\n%s", species);
}
int My_atoi(char cad[10]) {
int r = 0;
int i;
for (i = 0; cad[i] != '\0'; i++) {
r = r * 10;
r += cad[i] - '0';
}
return r;
}
void list_species() {
}
void stadistics() {
}
void executeOption(int op) {
switch (op) {
case 1:
New_species();
break;
case 2:
list_species();
break;
case 3:
stadistics();
break;
default:
break;
}
}
int main() {
int op = 0;
do {
op = menu();
executeOption(op);
} while (op != 4);
return 0;
}
I’ve seen that you can use files* so it can create a .txt file for storing but I don’t know how to use it and I don't think that it's allowed in this program.
I'll leave a photo of how it should work
Thanks.
ok u need to save data to a file and load from a file.
here a short code of my and read and write:
#include<stdio.h>
#include<stdlib.h>
typedef struct worker
{
int sal;
char name[25];
}W;
void main()
{
FILE *f;
int i,j=4;
W a[3];
while(j!=3)
{
printf("\nEnter\n[1]write\n[2]read\n[3]exit\n");
scanf("%d",&j);
if(j==1)
{
if (f==NULL)
{
printf("Error!!\n");
exit(0);
}
f=fopen("workers.txt","w");
for(i=0;i<3;i++)
{
printf("\nEnter worker name: ");
scanf("%s",&a[i].name);
printf("\nEnter worker sal: ");
scanf("%d",&a[i].sal);
fprintf(f,"%s %d",a[i].name,a[i].sal);
}
if(j==2)
{
if (f==NULL)
{
printf("Error!!\n");
exit(0);
}
f=fopen("workers.txt","r");
for(i=0;i<3;i++)
{
fscanf(f,"%s %d",a[i].name,&a[i].sal);
printf("\n%s %d",a[i].name,a[i].sal);
}
}
}
fclose(f);}
and I don't think that it's allowed in this program
why wouldn't you be allowed? Yes indeed you can go through two alternatives
To text file
This is the one proposed by dor in his answer where he shows you the way of writing text through fprintf.
To binary file
You can also write to a file using fwrite/fseek like this example I found surfing around you can check it out here -> c-tutorial-binary-file-io
#include<stdio.h>
/* Our structure */
struct rec
{
int x,y,z;
};
int main()
{
int counter;
FILE *ptr_myfile;
struct rec my_record;
ptr_myfile=fopen("test.bin","wb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for ( counter=1; counter <= 10; counter++)
{
my_record.x= counter;
fwrite(&my_record, sizeof(struct rec), 1, ptr_myfile);
}
fclose(ptr_myfile);
return 0;
}
and retrieving back the data from the binary may go this way as the tutorial shows
#include<stdio.h>
/* Our structure */
struct rec
{
int x,y,z;
};
int main()
{
int counter;
FILE *ptr_myfile;
struct rec my_record;
ptr_myfile=fopen("test.bin","rb");
if (!ptr_myfile)
{
printf("Unable to open file!");
return 1;
}
for ( counter=1; counter <= 10; counter++)
{
fread(&my_record,sizeof(struct rec),1,ptr_myfile);
printf("%d\n",my_record.x);
}
fclose(ptr_myfile);
return 0;
}
If you are looking for a solution in a .txt file I have a proposal,
#include <stdio.h>
int main(){
FILE *in;
FILE *OUT = fopen("read_at.txt", "w");
char name[20];
char capture[80];
int age = 0;
float grade = 0;
puts("introduce your name:");
scanf("%19s", name);
puts("introduce your age:");
scanf("%i", &age);
puts("introduce your Math grade(0-10):");
scanf("%f", &grade);
fprintf(OUT, "Age %i, Grade %f, Name %s\r\n", age, grade, name);
fclose(OUT);
if(!(in = fopen("read_at.txt","r"))){
fprintf(stderr, "The file could not be opened. \n");
return 1;
}
while (fscanf(in, "Age %i, Grade %f, Name %20[^\n]\n", &age, &grade, name)==3){
printf("A %i years old student has achieved a %f mark in last math exam, that student is: %s", age,grade, name);
}
fclose(in);
}
In this code that I have just created you can see how you can just create one file and read and get its data if it has a concrete format. If you are looking for a database you can just put values separated by “;” and new lines (\n). With that if you save it as .csv you would obtain an excel sheet and quite a good database.
If you are interested in this solution, just let me know if you need any additional help.
Regards,

Resources