execution problem in read/write from file exercise (newbie) - c

i wrote a programe to read integers from a .txt file and put them in an array, it compiles just fine ,but would ask for the number of integers then stops
#include <stdlib.h>
#include <stdio.h>
void genererN ( int n){
int i=0;
FILE* fichier = NULL;
fichier=fopen("valeurs.txt","w");
while (i<n){
fprintf(fichier,"\n%d\n",rand());
i++;
}
}
void replirtab (int **t,int n){
int i=0;int m;
FILE* fichier = NULL;
fichier=fopen("valeurs.txt","r");
char stre[999999] = "";
while(i<n){
fgets(stre, 999999, fichier);
m = atoi(stre);
*t[i]=m;
i++;
}
}
void affichertab (int *t,int n){
int i=0;
while(i<n){
printf("%d\n",t[i]);
i++;
}
}
and this is my main function where i ask for the number of randomly generated integers and use my functions
#include <stdio.h>
#include <stdlib.h>
#include "source1.h"
int main()
{
int n;
printf("donner le nombre de valeurs ");
scanf("%d",&n);
int T[n];
genererN(n);
replirtab(T,n);
affichertab(T,n);
return 0;
}
and the header
#ifndef SOURCE1_H_INCLUDED
#define SOURCE1_H_INCLUDED
void genererN ( int n);
void replirtab (int *t,int n);
void affichertab (int *t,int n);
#endif // SOURCE1_H_INCLUDED

Fix the following problems:
You're not closing the file after you write it, so the buffer isn't being flushed.
You're writing an extra newline before each number, but you don't skip it when reading.
replirtab() expects an array of pointers, but the array contains integers, not pointers. There's no need to indirect through the references. When you pass an array to a function, a pointer to the first element is passed.
#include <stdlib.h>
#include <stdio.h>
void genererN ( int n){
int i=0;
FILE* fichier = NULL;
fichier=fopen("valeurs.txt","w");
if (!fichier) {
printf("Unable to write file\n");
exit(1);
}
while (i<n){
fprintf(fichier,"%d\n",rand());
i++;
}
fclose(fichier);
}
void replirtab (int *t,int n){
int i=0;int m;
FILE* fichier = NULL;
fichier=fopen("valeurs.txt","r");
if (!fichier) {
printf("Unable to read file\n");
exit(1);
}
char stre[999999] = "";
while(i<n){
fgets(stre, 999999, fichier);
m = atoi(stre);
t[i]=m;
i++;
}
fclose(fichier);
}
void affichertab (int *t,int n){
int i=0;
while(i<n){
printf("%d\n",t[i]);
i++;
}
}

Related

Unable to read a structure from a text file in C

#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int id;
char* name;
float weight;
} Person;
int main()
{
Person *person=malloc(10*sizeof(Person));
int i=0;
char row[20];
FILE *input=fopen("input.txt","r+");
while(fscanf( input, "%s", &row)>0) i++;
i/=5;
printf("%d\n", i);
fseek(input,0,SEEK_SET);
int j;
char string[20];
for (j=0;j<i;j++){
fscanf(input,"%s",string);
fscanf(input,"ID:%d",&person[j].id);
fscanf(input,"Name:%s",person[j].name);
fscanf(input,"Weight:%f",&person[j].weight);
fscanf(input,"%s",string);
}
fclose(input);
//Person:{
//ID:1214124141
//Name:Trump
//Weight:101.50
//}
//Person:{
//ID:5235252525
//Name:Obama
//Weight:78.30
//}
return 0;
}
Hello!
I want to read a structure from a file, but my array person contains only 0 even after I read from the file. My input file has the structure shown in the comment lines.
What am I not doing well?
Thanks a lot for the help!
fix like this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
long long int id;//32bit int can't hold like 5235252525
char name[20];//Allocate space
float weight;
} Person;
#define FORMAT "%*s ID:%lld Name:%19[^\n] Weight:%f %*s"
int main(void){
FILE *input=fopen("input.txt", "r+");
if(!input){
perror("fopen");
return -1;
}
int n = 0;
Person p;
while(3==fscanf(input, FORMAT, &p.id, p.name, &p.weight))
++n;
printf("number of record: %d\n", n);
Person *person = malloc(n * sizeof(Person));
if(!person){
perror("malloc");
fclose(input);
return -2;
}
rewind(input);
for (int i = 0; i < n; ++i){
fscanf(input, FORMAT, &person[i].id, person[i].name, &person[i].weight);
}
fclose(input);
//check print
for (int i = 0; i < n; ++i){
printf("ID:%lld, Name:%s, Weight:%.2f\n", person[i].id, person[i].name, person[i].weight);
}
free(person);
return 0;
}

Seg Fault occurs while malloc-ing

This function is a part of program which will gain statistics about books (amount of specific letters, words etc.). Thing is that segmentation fault appears when trying to malloc:
*wordArray[arrayIndex] = malloc(sizeof(***wordArray)*(wcslen(newWord)+1));
after reallocing whole array
*wordArray = realloc(*wordArray, (arrayIndex+1)*sizeof(**wordArray));
I know that realloc isn't really efficent but the most important thing at the moment is to understand why it doesn't work at all. Thanks a lot.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#include <wctype.h>
#include <wchar.h>
#define X 2
void wordManager(wchar_t ***, int **, wchar_t *);
int main(int argc, char **argv){
setlocale(LC_ALL, "");
wchar_t **wordArray;
int *wordAmount;
wchar_t word[50];
for(int i=0; i<X; i++){
scanf("%ls", word);
wordManager(&wordArray, &wordAmount, word);
}
for(int i=0; i<X; i++){
printf("%ls; %d times\n", wordArray[i], wordAmount[i]);
}
}
void wordManager(wchar_t ***wordArray, int **wordAmount, wchar_t *newWord){
static int isArrayInitialised = 0;
static int isArrayEmpty = 1;
static int arrayIndex = 0;
int wordLocation;
if(!isArrayInitialised){
*wordArray = malloc(sizeof(**wordArray)*1);
if(*wordArray==NULL){
printf("Error mallocing wordArray");
exit(EXIT_FAILURE);
}
*wordAmount = calloc(1, sizeof(*wordAmount));
if(*wordAmount==NULL){
printf("Error callocing wordAmount");
exit(EXIT_FAILURE);
}
isArrayInitialised = 1;
}
if(isArrayEmpty){
*wordArray[0] = malloc(sizeof(***wordArray)*(wcslen(newWord)+1));
wcscpy(*wordArray[0], newWord);
*wordAmount[0] = 1;
isArrayEmpty = 0;
}
else{
//Check if word is already in an array.
wordLocation = 0;
for(; wordLocation<arrayIndex+1; wordLocation++){
if(!wcscmp(*wordArray[wordLocation], newWord)) break;
}
printf("%d\n", wordLocation);
//Word hasn't been found. Then:
if(wordLocation==arrayIndex+1){
arrayIndex++; //Increase arrays' volume.
*wordArray = realloc(*wordArray, (arrayIndex+1)*sizeof(**wordArray));
if(*wordArray==NULL){
printf("Error reallocating wordArray memory.\n Array index: %d", arrayIndex);
exit(EXIT_FAILURE);
}
*wordAmount = realloc(*wordAmount, (arrayIndex+1)*sizeof(**wordAmount));
if(*wordAmount==NULL){
printf("Error reallocating wordAmount memory.\n Array index: %d", arrayIndex);
exit(EXIT_FAILURE);
}
*wordArray[arrayIndex] = malloc(sizeof(***wordArray)*(wcslen(newWord)+1));
wcscpy(*wordArray[arrayIndex], newWord);
*wordAmount[arrayIndex] = 1;
}
//Word has been found in an array.
else{
(*wordAmount[wordLocation])++;
}
}
}

First use of headers in c and really not understanding it well

I using first time the HEADERS in c so I'm not understanding it well.
main.c
#include <stdio.h>
#include <stdlib.h>
#include "kibe.h"
int main()
{
int a[5],n,i;
beolvas(a,n,"be.txt");
kiir(a,n);
return 0;
}
kibe.h
#ifndef KIBE_H_INCLUDED
#define KIBE_H_INCLUDED
void beolvas(int*, int, const char *);
void kiir(int*, int);
#endif // KIBE_H_INCLUDED
kibe.c
#include <stdio.h>
#include <stdlib.h>
void beolvas(int *a,int n,const char * file)
{
int i;
FILE * fin;
fin = fopen("be.txt", "rt");
fscanf(fin,"%i",&n);
a = (int*)malloc(n*sizeof(int));
for(i = 0; i < n; ++i){
fscanf(fin,"%i",&a[i]);
}
free(a);
}
void kiir(int *a,int n)
{
int i;
for(i = 0; i < n; ++i){
printf("%i ",a[i]);
}
}
The problem is that I get memory garbage every time and the file contains five numbers which must be read and written to monitor. If I write the void kiir is code to void beolvas function it works well.
You allocate dynamic memory in your function beolvas but you never pass it out of the function. Your parameters a and n have to be output parameters, so you have to change your function signature. Apart form this use fclos to close the file. Adapt your code like this:
kibe.c
void beolvas( int **a, int *n, const char * file )
// ^^ ^ output paramters a and n
{
FILE * fin;
fin = fopen("be.txt", "rt");
fscanf( fin, "%i", n ); // read number of elements
// ( n is a pointer to an int )
*a = malloc( *n * sizeof(int) ); // allocate memors
for ( int i = 0; i < n; ++i)
{
fscanf(fin,"%i",(*a)+i); // read one element
// ( *a is the pointer to the dynamic memory,
// so (*a)+i is a pointer to (*a)[i] )
}
fclose(fin);
}
kibe.h
void beolvas( int**, int* , const char *);
main.c
int main()
{
int a* = NULL;
int n = 0;
beolvas( &a, &n,"be.txt");
// ^ ^
kiir( a, n );
free(a); // free the memory which was allocated inside function beolvas
return 0;
}

getting fscanf to store in structs in C

I have an assignment where I need to get Values of RLC circuits from a file and calculate the resonant frequency however my issue is when I use the fscanf function it reads only the first line of the file and the rest comes out as zeros .
#include <stdio.h>
data
int h;
typedef struct cct
{
int code[50];
float R[50];
float L[50];
float C[50];
} CCT;
int read(CCT cct[], int n_p, FILE* fp){
char temp;
if(fp==NULL){
printf("Error\n");
return -1;
}
fscanf(fp,"%d,%f,%e,%e\n", cct[n_p].code, cct[n_p].R,cct[n_p].L, &cct[n_p].C);
}
int main()
{
FILE* fp = fopen("U://datafile.txt", "rt");
int i = 0;
CCT cct[50];
int size;
while (!feof(fp)) {
read(cct, i, fp);
i++;
}
size = i;
for (i = 0; i < size; ++i)
printf("%d,%0.2f,%0.2f,%0.2f\n", cct[i].code[i], cct[i].R[i],
cct[i].L[i], cct[i].C[i]);
scanf("%d",&h);
fclose(fp);
}
and this is the data file
1,4.36,2.23e-2,4.65e-8
2,4.57,2.01e-2,5.00e-8
3,3.99,2.46e-2,4.82e-8
4,4.09,2.60e-2,4.70e-8
I would appreciate if someone could point put why it only gets the first line. Thanks
CCT is composed of multiple arrays (you have arrays of arrays, which is wrong for the exercise, but that's not the point) and you always write to the element zero of the arrays. For example, cct[n_p].code in fscanf() is the address of the array, which is identical to the address of cct[n_p].code[0]. Then you print code[i] in the output loop, which is blank except for i == 0.
fscanf(fp,"%d,%f,%e,%e", cct[n_p].code, cct[n_p].R,cct[n_p].L, cct[n_p].C);
...
printf("%d,%0.2f,%0.2f,%0.2f\n", cct[i].code[0], cct[i].R[0], cct[i].L[0], cct[i].C[0]);
Something like the following, perhaps
#include <stdio.h>
typedef struct cct {
int code;
float R;
float L;
float C;
} CCT;
int h;
int read(CCT cct[], int n_p, FILE* fp){
char temp;
if(fp==NULL){
printf("Error\n");
return -1;
}
fscanf(fp,"%d,%f,%e,%e\n", &cct[n_p].code, &cct[n_p].R, &cct[n_p].L, &cct[n_p].C);
}
int main(){
FILE* fp = fopen("U://datafile.txt", "rt");
int i = 0;
CCT cct[50];
int size;
while (!feof(fp)) {
read(cct, i, fp);
i++;
}
size = i;
for (i = 0; i < size; ++i)
printf("%d,%0.2f,%0.2f,%0.2f\n", cct[i].code, cct[i].R, cct[i].L, cct[i].C);
scanf("%d",&h);
fclose(fp);
}

Using a char array as input to module to scan a file in C

I am trying to use the getStats function twice - once for each input file. I am supposed to be using a char array called statFile[]to pass as the argument to the prototype to select which file it is to work with. Currently I know how to use one file at a time (by explicit naming the file in the prototype) to make it work, but do not understand how to use it for both inputs. Thanks in advance!
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define AUBURN "auburn2013.txt" //input data files
#define ALABAMA "alabama2013.txt" //input data files
#define NUMGAMES 13
int getStats( char statFile[], int compPass[], int attPass[], int numYds[], int numTD[] );
void analysis( int compPass[], int attPass[], int numYds[], int numTD[], double aveYds[], double pectCmp[], int tdPts[], int numGames[]);
int main(void)
{
int compPass[NUMGAMES],
attPass[NUMGAMES],
numYds[NUMGAMES],
numTD[NUMGAMES];
double bamaStats,
auburnStats,
setAuburn,
setBama;
FILE *au = fopen("auburn2013.txt","r");
FILE *al = fopen("alabama2013.txt","r");
if (al == NULL)
printf("Error Opening File\n");
else if (au == NULL)
printf("Error Opening File\n");
bamaStats = getStats(ALABAMA, compPass, attPass, numYds, numTD);
return 0;
}
int getStats( char statFile[], int compPass[], int attPass[], int numYds[], int numTD[] )
{
int i,
p,
k = sizeof(compPass[NUMGAMES]);
FILE *al = fopen("alabama2013.txt","r");
while (fscanf(al ,"%d %d %d %d", &compPass[i], &attPass[i], &numYds[i], &numTD[i]) !=EOF)
{
i++;
}
printf("Number of Games with data: %d\n", i);
for(p=0; p<8 ; p++)
{
printf("%d %d %d %d\n", compPass[p], attPass[p], numYds[p], numTD[p]);
}
return 0;
}
You are already passing in the stat file name, so need to change:
FILE *al = fopen("alabama2013.txt","r");
to
FILE *al = fopen(statFile,"r");
You can do that like this:
#include <stdio.h>
#include <assert.h>
void print_fname(char **farray, int fnum)
{
int i;
assert(farray != NULL);
for (i = 0; i < fnum; ++i) {
assert(farray[i] != NULL);
printf("file name %d: %s\n", i + 1, farray[i]);
}
}
int main()
{
char *farray[] = {"file1", "file2"};
print_fname(farray, 2);
return 0;
}
Hope can help.

Resources