Add item sorted into a file in c - c

I need to take a .txt file, and check the scores that exist in it, if my score is among the top 5, add my score and my name to the file, in the correct order. But in the way I did, the append, only adds at the end. Would there be any way to check the points that are in the file, to make the comparison?
Example: If my points are greater than 40, put my name and number of points first. Leaving the rest of the list sorted again.
pedro=40
joao=32
claudio=10
joao=2
Rick=0
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
int main() {
char teste[1000], nome[20];
int meuPonto=0;
FILE *pontos;
pontos = fopen("dados.txt", "r");
if(pontos == NULL){
exit(1);
}
printf("Pontuacao atual:\n");
while(fgets(teste, 1000, pontos)){
printf("%s\n", teste);
}
printf("Digite seu nome e seus pontos:\n");
scanf("%s %i", nome, &meuPonto);
fclose(pontos);
pontos = fopen("dados.txt", "a");
fprintf(pontos, "\n%s\n%d", nome, meuPonto);
fclose(pontos);
}
The file can start at zero, but you have to save the score that was written.

Initialise an array[MAX_SCORE] with empty lines.
Add your line to the array according to your score, array[your_score].
Read each line into array[line_score].
If you get duplicates (position not empty), append the line after a LF.
Finally, print the array (backwards) to a new file (or overwrite the old file). (skip empty lines).

Related

C Program to count keywords from a keyword text file in a fake resume and display the result

#EDIT: I think the problem is that I put my 2 text files on desktop. Then, I move them to the same place as the source file and it works. But the program cannot run this time, the line:
cok = 0;
shows "exception thrown".
// end EDIT
I have the assignment at school to write a C program to create 2 text files. 1 file stores 25 keywords, and 1 file stores the fake resume. The problem is, my program cannot read my keywords.txt file. Anyone can help me? Thank you so much.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//*****************************************************
// MAIN FUNCTION
int main()
{
//File pointer for resume.txt file declared
FILE *fpR;
//File pointer for keywords.txt file declared and open it in read mode
FILE* fpK = fopen("keywords.txt", "r");
//To store character extracted from keyword.txt file
char cK;
//To store character extracted from resume.txt file
char cR;
//To store word extracted from keyword.txt file
char wordK[50];
//To store word extracted from resume.txt file
char wordR[50];
//To store the keywords
char keywords[10][50];
//To store the keywords counter and initializes it to zero
int keywordsCount[10] = { 0, 0, 0, 0 };
int coK, coR, r, r1;
coK = coR = r = r1 = 0;
//Checks if file is unable to open then display error message
if (fpK == NULL)
{
printf("Could not open files");
exit(0);
}//End of if
//Extracts a character from keyword.txt file and stores it in cK variable and Loops till end of file
while ((cK = fgetc(fpK)) != EOF)
{
//Checks if the character is comma
if (cK != ',')
{
//Store the character in wordK coK index position
wordK[coK] = cK;
//Increase the counter coK by one
coK++;
}//End of if
//If it is comma
else
{
//Stores null character
wordK[coK] = '\0';
//Copies the wordK to the keywords r index position and increase the counter r by one
strcpy(keywords[r++], wordK);
//Re initializes the counter to zero for next word
coK = 0;
fpR = fopen("resume.txt", "r");
//Extracts a character from resume.txt file and stores it in cR variable and Loops till end of file
while ((cR = fgetc(fpR)) != EOF)
{
//Checks if the character is space
if (cR != ' ')
{
//Store the character in wordR coR index position
wordR[coR] = cR;
//Increase the counter coR by one
coR++;
}//End of if
else
{
//Stores null character
wordR[coR] = '\0';
//Re initializes the counter to zero for next word
coR = 0;
//Compares word generated from keyword.txt file and word generated from resume.txt file
if (strcmp(wordK, wordR) == 0)
{
//If both the words are same then increase the keywordCounter arrays r1 index position value by one
keywordsCount[r1] += 1;
}//End of if
}//End of else
}//End of inner while loop
//Increase the counter by one
r1++;
//Close the file for resume
fclose(fpR);
}//End of else
}//End of outer while loop
//Close the file for keyword
fclose(fpK);
//Display the result
printf("\n Result \n");
for (r = 0; r < r1; r++)
printf("\n Keyword: %s %d time available", keywords[r], keywordsCount[r]);
}//End of main
I think the problem is the text files, aren't they?
The name of my 1st test file is "keywords.txt", and its content is:
Java, CSS, HTML, XHTML, MySQL, College, University, Design, Development, Security, Skills, Tools, C, Programming, Linux, Scripting, Network, Windows, NT
The name of my 2nd test file is "resume.txt", and its content is:
Junior Web developer able to build a Web presence from the ground up -- from concept, navigation, layout, and programming to UX and SEO. Skilled at writing well-designed, testable, and efficient code using current best practices in Web development. Fast learner, hard worker, and team player who is proficient in an array of scripting languages and multimedia Web tools. (Something like this).
I don't see any problem with these 2 files. But my program still cannot open the file and the output keeps showing "Could not open files".
while ((cK = fgetc(fpK)) != EOF)
If you check the documentation, you can see that fgets returns an int. But since cK is a char, you force a conversion to char, which can change its value. You then compare the possibly changed value to EOF, which is not correct. You need to compare the value that fgets returns to EOF since fgetc returns an EOF on end of file.

C - sscanf ignoring comma from csv file and reading the same piece of data twice

I am trying to read from a CSV file into struct. For some reason, the value for social security numbers is also reading the address and them the address is being read a second time into newBin.address. It looks like the sscanf is ignoring the comma that separates the socials and address when it reads the file but then does register it when it moves on reading the address. Any help is appreciated.
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
#define STRSIZE 70
typedef struct BIN_DATA {
unsigned int user_number;
char name[32];
char social_security[10];
char address[32];
} BIN_DATA;
int main()
{
// Define variables.
FILE *in, *out;
char str[STRSIZE];
// New BIN.
BIN_DATA newBin;
// Open files.
in = fopen("updated.txt", "r");
// Check files.
if(in == NULL)
{
puts("Could not open file");
exit(0);
}
while(fgets(str, STRSIZE, in) != NULL)
{
memset(&newBin, '\0', sizeof(BIN_DATA));
sscanf(str, "%6u, %[^,], %[^,], %[^\n\r]", &newBin.user_number, newBin.name,\
newBin.social_security, newBin.address);
printf("%u. %s. %s. %s.\n", newBin.user_number, newBin.name,\
newBin.social_security, newBin.address);
}
return 0;
}
File being read:
289383,Estefana Lewey,591-82-1520,"9940 Ohio Drv, 85021"
930886,Burl Livermore,661-18-3839,"226 Amherst, 08330"
692777,Lannie Crisler,590-36-6612,"8143 Woods Drv, 20901"
636915,Zena Hoke,510-92-2741,"82 Roehampton St, 47905"
747793,Vicente Clevenger,233-46-1002,"9954 San Carlos St., 55016"
238335,Lidia Janes,512-92-7402,"348 Depot Ave, 29576"
885386,Claire Paladino,376-74-3432,"587 Front Ave, 32703"
760492,Leland Stillson,576-55-8588,"9793 Boston Lane, 08610"
516649,Wes Althouse,002-58-0518,"8597 Annadale Drive, 06514"
641421,Nadia Gard,048-14-6428,"218 George Street, 29150"
As mentioned in the comments, the social_security member does not allocate enough space to hold the data you're reading. It needs to be at least 12 to hold the SSN as written with a terminator at the end.
As for the format string you use with sscanf(), it's nearly correct. However, you'll want to bound the maximum string length to match what you have storage for, so for example with name of 32 you should limit it to 31 characters saving one at the end for the terminator.
I changed the social_security field to char social_security[12]; and then changed the format string to sscanf to be the following:
"%6u, %31[^,], %11[^,], %31[^\n\r]"
I was able to run the modified code with the sample input file to get the output you described. You can try it too at the link:
Runnable code

C Transforming array into string using sprintf

I have scanned "ABCDEFGHIJK" with fscanf into a char array[26]. Then I got "ABCDEFGHIJK" using "for" into another array[11]. Now I need to get to an "ABCDEFGHIJK.mp4" array[15] in order to feed that filename into a rename function.
I don't know much about C programming besides printf, scanf, for and while.
sprintf(filename, "%c%c%c%c%c%c%c%c%c%c%c.mp4", codigo[0], codigo[1], codigo[2], codigo[3], codigo[4], codigo[5], codigo[6], codigo[7], codigo[8], codigo[9], codigo[10]);
This code above seems to work, but I wonder if there is a simpler way (especially for bigger arrays)?
Clarification: I have a txt file, formatted with these containing the filenames without extension and the human filename. I'm trying to make a program that will rename these files to the correct name, as they are from a backup that failed.
EDIT: Here is the full program. I renamed the variables to make more sense, so "codigo" is now "idcode".
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int i, j, k;
char value1[26], value2[70], idcode[11], filename[16], fullname[64], filenamestring[16], fullnamestring[64];
// Opening file.
FILE *nomes;
nomes = fopen("/Users/EA/Desktop/Songs/backup.txt", "rt");
if(nomes == NULL)
{
printf("Erro ao abrir backup.txt");
exit(1);
}
// Skipping beggining of file until first value.
for(i=0; i<10; i++)
{
fscanf(nomes, "%*s");
}
// Reading first value, and repetition.
while(fscanf(nomes, "%s", value1) == 1)
{
j = k = 0;
// Extracting idcode from value1.
for(i=7; i<18; i++)
{
idcode[j] = value1[i];
j++;
}
// Filling the complete filename.
sprintf(filename, "%.*s.mp4", 11, idcode);
// Reading second value, the "human" filename.
fscanf(nomes, "\n%[^\n]", value2);
for(i=6; i<70; i++)
{
fullname[k] = value2[i];
k++;
}
// Transforming filenames into strings for rename function.
strncpy(filenamestring, filename, 16);
strncpy(fullnamestring, fullname, 64);
// Renaming the files.
rename(filename, fullname);
// Skipping useless data before the next cycle.
for(i=0; i<9; i++)
{
fscanf(nomes, "%*s");
}
}
// Closing file and ending program.
fclose(nomes);
return(0);
}
It looks like you got an array of char's.
You can simply do:
sprintf(filename, "%.*s.mp4", 11, codigo)
You can read more about the %.*s specifier in this question.
If you just want to append the format ".mp4" to the end of the string the easiest way to do that is just:
strcat(filename,".mp4");
after you printed the name without the ".mp4" into it.
If you really want to use sprintf then i think this should suffice:
sprintf(filename,"%s.mp4", codigo);
Also,if you want your string to be bigger and not fixed in size you can put "\0" at the end of it(this might not work if you try to use the strings in other programming languages but c) with strcat as above,or you can do this:
memset(&filename, 0, sizeof(filename));

Specific data from txt file using C

Hello i have a text file that contains cities, dates and temperature. How can i read temperature from specific city and day? For example if I search for Alingsås 2014-05-14 I need to get 13.81, 11.59 and 13.81. The part I am stuck with is after i have opened the file and put variables for the city and date. Info is stored in the text file like this:
Alingsås;
2014-05-14;
13.81;
11.59;
13.81;
2014-05-15;
8.89;
7.99;
9.15;
2014-05-16;
6.2;
5.07;
6.58;
2014-05-17;
7.91;
5.55;
7.91;
2014-05-18;
7.76;
5.95;
7.76;
2014-05-19;
7.95;
6.91;
9.72;
2014-05-20;
18.45;
12.92;
18.45;
Arboka;
2014-05-14;
9.55;
4.53;
10.66;
2014-05-15;
6.33;
1.5;
9.37;
2014-05-16;
8.85;
3.4;
12.08;
2014-05-17;
14.01;
4.8;
15.4;
2014-05-18;
14.16;
6.35;
17.23;
2014-05-19;
21.39;
14.57;
21.39;
2014-05-20;
23.34;
14.82;
23.34;
My Code so far is
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>
int main(void)
{
FILE * fp;
char c;
// open file
fp =fopen("C:\\Users\\Karl\\Desktop\\info.txt", "r");
if (fp != NULL)
{ char city[10] = "Ålingsås";
int temp1;
int temp2;
int temp3;
char date[13] = "2014-05-14";
One solution is to make a structure that contains the name of the city, and a pointer to another structure which will be an "array" (dynamically allocated on the heap) and where each entry contains the data and the three temperatures.
Then read one line at a time from the file, trim the input (to remove the leading and trailing whitespace, if there is any) and create the above structure. If the current line starts with a digit it's a date and read three more lines for the temperature and fill in the structure. If the current line doesn't start with a digit then you have a new city, and you create a new city-structure.

C File Handling / Structure Problem

How does one read in a txt file containing names and marks of students and inputting them
into an array of structures.
maximum allowable records are 7:
e.g. James 45
Mary 70
Rob 100
First, define the structure. The structure describes what a record is; what data it contains. Here you have a student's name and his or her mark.
Second you need to prepare the array to write the objects of the structure into. You already know from the problem description that no more than 7 students are allowed, so you can define the length of the array to that number.
Next, open the text file.
Lastly write a loop that takes as input from the file a string for the student's name and an integer (or a floating-point point number if you so choose) for their mark. In the loop create a structure for each record and insert the structure into the array.
And of course, don't forget to close the file when you're done.
That's all there is to it. If you have any syntax or logic questions then ask in the comments, and we'll gladly help.
Read the man page for fopen: http://linux.die.net/man/3/fopen
This should give you somewhere to start.
Also, the man page for fread and fgets could be helpful. There are many ways to read from a file and the path you choose will depend on numerous things, such as the structure of the file and the amount of security you want in your application.
found this code that is similar enough that should be able to help you get done what you need.
#include <stdio.h>
#include <string.h>
/* Sample data lines
5 0 Wednesday Sunny
6 2 Thursday Wet
*/
int main() {
/* Define a daydata structure */
typedef struct {
int n_adults; int n_kids;
char day[10]; char weather[10];
} daydata ;
daydata record[30];
FILE * filehandle;
char lyne[121];
char *item;
int reccount = 0;
int k;
/* Here comes the actions! */
/* open file */
filehandle = fopen("newstuff.txt","r");
/* Read file line by line */
while (fgets(lyne,120,filehandle)) {
printf("%s",lyne);
item = strtok(lyne," ");
record[reccount].n_adults = atoi(item);
item = strtok(NULL," ");
record[reccount].n_kids = atoi(item);
item = strtok(NULL," ");
strcpy(record[reccount].day,item);
item = strtok(NULL,"\n");
strcpy(record[reccount].weather,item);
printf("%s\n",record[reccount].day);
reccount++;
}
/* Close file */
fclose(filehandle);
/* Loop through and report on data */
printf("Weather Record\n");
for (k=0; k<reccount; k++) {
printf("It is %s\n",record[k].weather);
}
}
http://www.wellho.net/resources/ex.php4?item=c209/lunches.c
Give a holler with code you tried if you have problems changing it to fit your needs.

Resources