I'm trying to write students' names and grades and read from inside the binary file, but it's not working.
I'm trying to do this without struct, because I didn't learn it yet.
Writing:
#include <stdio.h>
#include <stdlib.h>
#define Q 20
FILE *arq;
int main(int argc, char const *argv[])
{
char url[]="notas.bin";
char *dmain[Q];
arq = fopen(url,"wb");
if(arq == NULL)
{
printf("Erro, nao foi possivel abrir o arquivo\n");
exit(1);
}
for (int i = 1; i< argc; i++ )
{
dmain[i-1]=argv[i];
printf("%s\n", dmain[i-1]);
}
for (int i = 0; i < Q; i++)
{
fwrite(dmain+i, sizeof(char), 1, arq);
}
fclose(arq);
}
Reading:
#include <stdio.h>
#include <stdlib.h>
#define Q 20
#define N 10
int main (){
char url[]="notas.bin";
char *nomes[N];
int cont, nota[N], recebe[Q];
FILE *arq;
arq = fopen(url, "rb");
if(arq == NULL)
{
printf("Erro, nao foi possivel abrir o arquivo\n");
exit(1);
}
cont = fread(recebe, sizeof(char), Q, arq);
if (cont !=Q)
fprintf (stderr, "Foram lidos apenas %d Elementos!!!\n" , cont) ;
/* Apresentar os dados ao usuário */
for (int i=0; i<Q; i++)
printf ("%d N: %d \n", i+1, recebe[i]);
fclose(arq);
}
This is still the prototype, I was writing and the reading is kind of sus with numbers repeating:
Sending the data:
PS C:\\Users\\gabri\\OneDrive\\Documentos\\GitHub\\Programacao1\\Exercicio 7\> & ."prog4_escrever_arquivo_bin_notas.exe" gabriel 90 pedro 80 sandra 70 brenda 80 tiago 60 barbara 60 maria 90 ana 60 vitor 90 caze 70
gabriel
90
pedro
80
sandra
70
brenda
80
tiago
60
barbara
60
maria
90
ana
60
vitor
90
caze
70
Reading the data:
PS C:\\Users\\gabri\\OneDrive\\Documentos\\GitHub\\Programacao1\\Exercicio 7\> & ."prog5_ler_arquivo_bin_notas.exe"
1 N: 1614815232
2 N: -524246912
3 N: 1614815232
4 N: -524246912
5 N: -533675952
6 N: 654
7 N: -151458356
8 N: 32763
9 N: 2
10 N: 654
11 N: 0
12 N: 0
13 N: 974291712
14 N: 654
15 N: 268501009
16 N: 227
17 N: 976422744
18 N: 654
19 N: -151528186
20 N: 32763
Related
my friend is studying for an exam. He keeps receiving the segmentation fault on " while (fscanf(f, "%s %d %d", A[i].costruttore, A[i].ns, A[i].costo) != EOF)".
How can I help him?
You can find his code below
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DIM 100
typedef struct
{
char costruttore[20];
int ns;
int costo;
} memoria;
void lettura(memoria A[], int *n)
{
int i = 0;
FILE *f;
f = fopen("memory.txt", "r");
if( f == NULL ) {
fprintf(stderr, "Couldn't open %s: %s\n", "memory.txt", strerror(errno));
exit(1);
}
while (fscanf(f, "%s %d %d", A[i].costruttore, A[i].ns, A[i].costo) != EOF)
i++;
(*n) = i;
fclose(f);
for (i = 0; i < (*n); i++)
printf("%s %d %d\n", A[i].costruttore, A[i].ns, A[i].costo);
}
int main()
{
memoria A[DIM];
int n;
lettura(A, &n);
return 0;
}
memory.txt content
PerKele 56 41
AM-Silicon 49 41
JKR 33 50
Atlantic 57 62
JADA 50 50
JKR 40 51
Drast 28 35
SGUZ 73 55
JADA 29 46
FARSTIC 65 30
Drast 41 36
FRoW 48 67
FARSTIC 39 62
Drast 27 44
SGUZ 51 50
Drast 58 60
Liquid 41 71
SWP3 50 63
KRRAM 54 24
YTK 32 60
ALOE 37 57
HAL 53 39
AM-Silicon 59 50
Atlantic 24 42
ALOE 31 46
JADA 38 65
Nikit 48 49
PerKele 68 37
HAL 46 53
TOO 73 60
HAL 31 37
YTK 39 55
Nikit 57 47
FARSTIC 40 47
AM-Silicon 68 52
HAL 50 50
JADA 32 37
FRoW 47 53
SWP3 50 50
FRoW 52 52
JADA 63 58
Liquid 47 46
Drast 36 54
ALOE 44 30
HAL 39 33
Drast 48 41
SWP3 52 56
KRRAM 65 56
He tried to put the & in "A[i].costruttore, A[i].ns, A[i].costo" but it didn't work.
Save time, enable all compiler warnings
This is the #1 lesson here.
"%d" matches a int *, not an int in fscanf()
Use the address of an int.
// fscanf(f, "%s %d %d", A[i].costruttore, A[i].ns, A[i].costo)
fscanf(f, "%s %d %d", A[i].costruttore, &A[i].ns, &A[i].costo)
Do not use "%s" without a width
Use a width 1 less than the array count.
char costruttore[20];
...
// fscanf(f, "%s %d %d", A[i].costruttore, ...
fscanf(f, "%19s %d %d", A[i].costruttore, ...
Do not compare against EOF
fscanf(f, "%s %d %d"... can return EOF, 1, 2, 3 (and maybe 0). Rather than test against 1 undesirable value compare against the desired result.
// while (fscanf(f, "%s %d %d", A[i].costruttore, A[i].ns, A[i].costo) != EOF)
while (fscanf(f, "%s %d %d", A[i].costruttore, A[i].ns, A[i].costo) == 3)
As #jabberwocky noted, pointers are needed within the fscanf, however these are only needed for the costo and ns fields.
Here's an equivalent example of OPs code, with the correct structure:
#include <stdio.h>
#define DIM 100
typedef struct record {
char f0[20];
int f1, f2;
} record_t;
int main (void) {
FILE *f = fopen("memory.txt", "r");
record_t records[DIM];
int i = 0;
while (fscanf(f, "%s %d %d", records[i].f0, &records[i].f1, &records[i].f2) != EOF) {
i++;
}
fclose(f);
}
This runs, and produces the correct results. Without the & in front of f1 and f2, it will segfault.
To scan two files which only include numbers. Combining and sorting all of the numbers. I have tried so many times but it still pops up an error message.
Please tell me if anyone knows where the problem is. Thank you so much!!!
#include<stdio.h>
#include<stdlib.h>
#define N 128
int main(){
int i, j, temp, count=0;
int data1[N];
char fname1[N], fname2[N];
scanf("%s", fname1);
FILE *f1 = fopen(fname1, "r");
while(1){
fscanf(f1, "%d", &data1[i]);
i++;
if(feof(f1)){
break;
}
count++;
}
fclose(f1);
scanf("%s", fname2);
FILE *f2 = fopen(fname2, "r");
while(1){
fscanf(f2, "%d", &data1[i]);
i++;
if(feof(f2)){
break;
}
count++;
}
fclose(f2);
for(j=count; j>1; j--){
for(i=0; i<j-1; i++){
if(data1[i]>data1[i+1]){
temp = data1[i];
data1[i] = data1[i+1];
data1[i+1] = temp;
}
}
}
for(i=0; i<count; i++){
printf("%d ", data1[i]);
}
return 0;
}
The inputs:
2 5 9 10 15 18 18 20 30 58
1 3 10 12 19 22 25 28 40
The output:
1 2 3 5 9 10 10 12 15 18 18 19 20 20 22 25 28 30 58
This question already has answers here:
Why is scanf() causing infinite loop in this code?
(16 answers)
Closed 8 years ago.
This Code does what it should do, as long as you really type an integer, as it asks you in line 10, but if you type a letter of something that isn't an integer it just prints out the lines 10 and 14 over and over and I really don't understand why, shouldn't it check the conditions for the while loop before it executes it another time?
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <time.h>
4
5 int raten(int zuErraten){
6 int geraten = 0, check = 1, versuche = 0;
7 while (versuche < 100 || geraten != zuErraten) {
8 versuche++;
9 printf("%i\n", versuche);
10 printf("Gib eine Zahl zwischen 1 und 100 ein:\n");
11 check = scanf("%i", &geraten);
12
13 if (check == 0) {
14 printf("Gib lediglich eine Zahl ein und drücke Enter:\n");
15 check = 1;
16 geraten = 0;
17 continue;
18 }
19
20 if (geraten < 1 || geraten > 100){
21 printf("Die Zahl sollte wirklich zwischen 1 und 100 sein, wobei 1 und 100 auch erlaubt sind!\n");
22 continue;
23 }
24
25 if (geraten < zuErraten) {
26 printf("Du hast %i geraten, diese Zahl ist leider zu klein!\n", geraten);
27 }
28
29 if (geraten > zuErraten) {
30 printf("Du hast %i geraten, diese Zahl ist leider zu groß!\n", geraten);
31 }
32
33 }
34
35 return versuche;
36 }
37
38 int main (int argc, char **argv){
39 time_t t;
40 srand((unsigned) time(&t));
41 int zuErraten, geraten, versuche;
42
43 zuErraten = (rand()%100) + 1;
44 printf("%i\n", zuErraten);
45 versuche = raten(zuErraten);
46 printf("Herrzlichen Glückwunsch, du hast die Zahl erraten.\nDu hast dafür %i Versuche gebraucht!\n", versuche);
47 }
It's because scanf doesn't remove whatever is in the input buffer if it doesn't match the format. So the next iteration it will read exactly the same input again, and fail. And again, and again...
I suggest you use e.g. fgets to read the input, and then use sscanf to parse it.
Here is my program, you can just ignore the main part:
#include<stdio.h>
#include<string.h>
typedef struct{
char firstname[20];
char lastname[20];
int assignments[5];
int labs[5];
int midterm;
int finalM;
}myclass;
myclass gng1105[10];
void update();
void printList();
void addStudent();
int main(){
int option;
update();
while(option!= 3){
printf("Please enter the option number:\n1.View the information for a specific student\n2.add a student number\n3.Exist\n");
scanf("%d", &option);
if(option == 1){
printList();
}
else if (option == 2){
addStudent();
}
else if (option == 3){
printf("system closed");
break;
}
else{
printf("invalid input");
}
printf("******************************************************************************\n");
}
return 0;
}
void update(){
FILE *fp;
fp = fopen("myclass.txt", "r");
int i = 0;
if (fp == NULL)
printf("Error opening file\n");
else{
while(!feof(fp)){
fscanf(fp,"%s%s%d%d%d%d%d%d%d%d%d%d%d%d", gng1105[i].firstname,
gng1105[i].lastname,
&gng1105[i].assignments[0],
&gng1105[i].assignments[1],
&gng1105[i].assignments[2],
&gng1105[i].assignments[3],
&gng1105[i].assignments[4],
&gng1105[i].labs[0],
&gng1105[i].labs[1],
&gng1105[i].labs[2],
&gng1105[i].labs[3],
&gng1105[i].labs[4],
&gng1105[i].midterm,
&gng1105[i].finalM);
i++;
}
}
fclose(fp);
}
void printList(){
int i;
for(i = 0;i <10 ; i++){
printf("%s %s %d %d %d %d %d %d %d %d %d %d %d %d", gng1105[i].firstname,
gng1105[i].lastname,
gng1105[i].assignments[0],
gng1105[i].assignments[1],
gng1105[i].assignments[2],
gng1105[i].assignments[3],
gng1105[i].assignments[4],
gng1105[i].labs[0],
gng1105[i].labs[1],
gng1105[i].labs[2],
gng1105[i].labs[3],
gng1105[i].labs[4],
gng1105[i].midterm,
gng1105[i].finalM);
}
}
void addStudent(){
}
Here is what txt file looks like:
Marcus Hill 100001 64 54 68 71 60 55 43 30 70 0 70 81
Brian Wyllie 100002 90 96 89 91 93 90 85 89 95 100 100 90
Soren Bjerg 100003 70 84 74 75 90 81 70 0 77 82 73 80
Jason Tran 100004 53 0 56 50 0 69 30 50 51 67 70 65
Alex Chu 100004 85 85 83 80 65 94 89 79 89 69 50 90
Here is the output, it looks so weird, even the error looks inconsistent(couldn't post image sorry):
Marcus Hill 100001 64 54 68 71 60 55 43 30 70 0 7081 brian 0 0 0 0 0 0 0 0 0 0 0 0Willie 10002 90 96 89 91 93 90 85 95 100 100 90soren Bjerg 1000003 70 84 74 75 90 81 70 0 77 82 7380 0 0 0 0 0 0 0 0 0 0 0 0
(I highlighted error, except those damn zeros)
I'd be really appreciate if anyone would help me!
Looks like you forgot a studentId field in your struct. You're assigning the student ID number (e.g. 100001) to gng1105[i].assignments[0].
Your struct should be defined like this:
typedef struct
{
char firstname[20];
char lastname[20];
int studentId; // <<<------ This is missing
int assignments[5];
int labs[5];
int midterm;
int finalM;
} myclass;
You need an extra format specifier and variable here:
fscanf(fp,"%s%s%d%d%d%d%d%d%d%d%d%d%d%d%", gng1105[i].firstname,
gng1105[i].lastname,
&gng1105[i].studentId, // <<<--- This is missing
&gng1105[i].assignments[0],
&gng1105[i].assignments[1],
&gng1105[i].assignments[2],
&gng1105[i].assignments[3],
&gng1105[i].assignments[4],
&gng1105[i].labs[0],
&gng1105[i].labs[1],
&gng1105[i].labs[2],
&gng1105[i].labs[3],
&gng1105[i].labs[4],
&gng1105[i].midterm,
&gng1105[i].finalM);
Don't forget this:
printf("%s %s %d %d %d %d %d %d %d %d %d %d %d %d %d", gng1105[i].firstname,
gng1105[i].lastname,
gng1105[I].studentId, // <<<--- Missing
gng1105[i].assignments[0],
gng1105[i].assignments[1],
gng1105[i].assignments[2],
gng1105[i].assignments[3],
gng1105[i].assignments[4],
gng1105[i].labs[0],
gng1105[i].labs[1],
gng1105[i].labs[2],
gng1105[i].labs[3],
gng1105[i].labs[4],
gng1105[i].midterm,
gng1105[i].finalM);
Don't forget fscanf and printf both need an extra %d.
Hello I have a litlle problem. I trying to make a bank wait time program but the time i read a 0 value with scanf() it do not read or read wrong. I did some search but noting that solves my problem.
this is the code.. its in C language.
#include <stdio.h>
int main(){
int c, n, t,i,d;//entradas do usuário (caixas, usuários, momento de chegada, tempo de atendimento
int menor_espera=0;// caixa de menor tempo de espera
int tempo_maximo = 20;// tempo maximo de espera por atencimento
int resultado=0;//Numero de pessoas com mais de 20 minutos de espera por atendimento
scanf(" %u %u %*c\n", &c, &n);// Lê o numero de caixas, numero de clientes no dia
if(c>0 && n>0){//iniciação só com valores positivos e possiveis c>1, n>1 (1 caixa e um cliente)
int caixa[c];// declara o um vetor de caixas
for(i=0;i<n;i++){// Loop de numero de usuários
scanf(" %u %u %*c\n", &t, &d);//Lê um cliente (T e D)
printf("print: %u %u\n", c, n);
int j;
for(j=0; j<c;j++){// loop de caixas
if(caixa[j]<caixa[menor_espera]){//chaca se o caixa atual é o primeiro caixa disponivel (caixa com menos tempo de uso)
menor_espera = j;//positivo, atualiza o caixa de menor espera
}
}if(caixa[menor_espera]-t>tempo_maximo){//checa se o cliente terá de esperar mais que o tempo maximo para ser atendido baseado na sua chegada
resultado++;//positivo, atualiza o contador de usuário que esperaram mais que o tempo maximo
}caixa[menor_espera] += d;// atualiza o tempo de uso do caixa que foi utilizado
}
printf("Resultado final: %d\n", resultado);// exibe resultado final
}getch();
}
and this is a input
1 16
0 10
0 10
0 10
3 10
5 10
7 10
11 10
13 10
14 10
15 10
16 10
17 10
18 3
19 10
20 10
23 3
that's the output i have
print: 10 0
print: 0 0
print: 0 3
print: 0 5
print: 0 7
print: 0 11
print: 0 13
print: 0 14
print: 0 15
print: 0 16
print: 0 17
print: 0 18
print: 19 10
print: 0 10
print: 3 3
print: 3 3
Resultado final: 16
but it shoud'nt look like this.
Tks for any help. if i found the solution i'll post here.
One issue is that you are not capturing or testing the return value from scanf(). It returns the number of items it parsed, or -1 on an i/o error.
Consider something like this to at least find out if this might be a problem:
if (scanf(" %u %u %*c\n", &t, &d) < 2) //Lê um cliente (T e D)
printf ("input conversion or i/o error\n");
This is problematic:
scanf(" %u %u %*c\n", &c, &n);
It looks for two numbers, some white space, and a non-white space character that is ignored, followed by more white space (which may or may not be a newline).
Given your input file, the first scanf() reads:
1 16
0
The next character to be read will be the 1 of the 10 on the second line of data. That's why you have problems.
Use fgets() to read a line at a time, and sscanf() to parse the line. And test the results of both fgets() and sscanf() (or scanf() if you insist on using it).
Here's an approximation to what you need.
#include <stdio.h>
int main(void)
{
int c, n, t,d;
int menor_espera = 0;
int tempo_maximo = 20;
int resultado = 0;
char line[4096];
if (fgets(line, sizeof(line), stdin) != 0)
{
if (sscanf(line, "%u %u", &c, &n) != 2)
return(1);
if (c > 0 && n > 0)
{
int caixa[c]; // VLA - uninitialized
for (int i = 0;i < n; i++)
{
if (fgets(line, sizeof(line), stdin) == 0)
break; // EOF or error
if (scanf(line, "%u %u", &t, &d) != 2)
break; // EOF or error
printf("print: %u %u\n", c, n); // Not t and d??
for (int j = 0; j < c; j++)
{
// Accessing uninitialized data in caixa array!
if (caixa[j] < caixa[menor_espera])
menor_espera = j;
}
if (caixa[menor_espera] - t > tempo_maximo)
resultado++;
caixa[menor_espera] += d;
}
printf("Resultado final: %d\n", resultado);
}
}
return(0);
}
I think there are some logic errors in the original code (some highlighted with comments), but I'm not sure what the corrections should be.