Read file of ints and load it into array - c

I have to open a file and read the numbers that are on it and then put these numbers in a array. I have the code below but it won't print me the numbers. I can't figure out why, can you guys help me?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
FILE *f;
int *ptr;
char inteiros[100];
int inteiros_b[100];
f=fopen("C:\\Users\\PC\\Documents\\Inteiros.txt", "r");
if(f==NULL)
{
printf("Error\n");
return 0;
}
else
printf("Success\n");
if(ptr==NULL);
return NULL;
while(fgets(inteiros, 100, f)!=NULL)
{
int i=0;
inteiros_b[i]=atoi(inteiros);
i++;
}
for(int i=0;i<100;i++)
printf("%d\n", inteiros_b[i]);
}

Use fscanf function
int main() {
FILE * file = fopen("C:\\Users\\PC\\Documents\\Inteiros.txt", "r");
int inteiros[100], i = 0, number;
if (file == NULL) {
printf("Error\n");
return 0;
} else printf("Success\n");
while (fscanf(file, "%d", & number) > 0) {
inteiros[i] = number;
i++;
}
fclose(file);
for (int i = 0; i < 100; i++)
printf("%d\n", inteiros[i]);
}

if(ptr==NULL);
return NULL;
You never assign ptr to anything, so wouldn't this code return NULL every time?
edit: also, should there be a semicolon after if(ptr==NULL)?

Related

Handling file reading in c

I'm having a problem with this program. I'm trying to send the pointer to the beginning of a file. It usually works but, when I send the file from one function to another, then fgets gets and empty string rather than the first row in the file.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int checkf(FILE *file, char*id){
char row[255];
int line_num = 1;
int find_result = 0;
char temp[255];
while (fgets(temp, 255, file) != NULL){ // here i get an Empty 'temp'
// so the contition is always false
if((strstr(temp, id)) != NULL) {
rewind(file);
for (int i=1; i<(line_num-1); i++) {
fgets(row, 255, file);
}
for (int i=0; i<4; i++) {
fgets(row, 255, file);
choppy(row);
printf("%s",row);
if (i!=3) {
printf(" ");
}
}
find_result++;
}
line_num++;
}
return find_result;
}
void add(FILE *file, char fileName[20]){
int check;
char name[100], id[100] ;
scanf("%s",name);
scanf("%s",id);
check = checkf(file,id);
if(check==0){
fputs("\n",file);
fputs(name,file);
}
}
int main(int argc, char * argv[]) {
// insert code here...
FILE *file;
FILE *file_app;
file_app= fopen(argv[argc-1], "a");
file= fopen(argv[argc-1],"r");
//check the there is a file
if (file== NULL)
{
printf("Can't open file");
return 1;
}
else
{
int cmd= strcmp(argv[1],"add");
if (cmd==0) add(file_app,argv[2]);
fclose(file);
printf("\n");
return 0;
}
}
So in conclusion, I think that when I the function checkf() is called from function add(), the file pointer gets lost. But, when I use checks() directly it works. Any ideas?

Segmentation fault 11 with pointers

why when attempt to use function N I get a Segmentation fault 11 .. im new to malloc so i dont exactly know where to look for my error .. im trying to read from a file and put certain line through fscanf to my double array ..
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
void V(int *id,int i,int *praca, double *plat,int *datum, FILE **f)
{
char meno[2000],priezvisko[2000];
if ((*f = fopen("zam.txt", "r")) == NULL)
{
printf("Neda sa otvorit");
// koniec programu
return ;
}
while(//vypis informacii zamestnancov
fscanf(*f,"%d %s %s %d %lf %d",&id[i],&meno[i],&priezvisko[i],&praca[i],&plat[i],&datum[i])>0)
{
printf(" osobne cislo zamestnanca:%d\n meno priezvisko:%s %s\n administrativa/vyrobny pracovnik:%d\n plat:%g\n datum:%08d\n\n",id[i],&meno[i],&priezvisko[i],praca[i],plat[i],datum[i]);
i++;
}
}
void N(int i,double **platy, FILE *f)
{
rewind(f);
int j=0,k=0;
char line[1800];
int suma = 0;
int count = 0;
int lineNumber = 2;
double val;
double d;
while(fgets(line, sizeof(line), f)!= NULL)
{
if (count == lineNumber)
{
suma++; //pocet platov
count++;
lineNumber+=6;
*platy=malloc(suma*sizeof(double));
fscanf (f, "%lf", platy[i]);
i++;
}
else
{
count++;
}
}
printf("SUMA: %d",suma);
}
int main() //MAIN
{
int i=0,id[1800],praca[1800],datum[1800];
char *meno[1800],*priezvisko[1800],z;
double plat[1800],*platy;
FILE *f;
while((z = getchar())!='K')
{
if(z == 'V')
V(id,i,praca,plat,datum,&f);
if(z == 'P')
P(i,praca,plat,datum,f);
if(z == 'N')
N(i,&platy,f);
}
/*
for (j=0 ; j<suma; j++) {
printf("%g\n",*platy[j]);
}
*/
return 0;
}

Counting word occurrences in a file C

Welcome everybody. I am new to Stackoverflow, I code in C for some time.
I have run to a problem writing a program counting word occurrences in a text file. I need to have an output telling what word occurred how many times. Here is the source code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int new_words=0;
int nwords=0;
typedef struct element{
char word[30];
int how_many;
} element;
int is_word_new(element ** dictionary, char * string)
{
for (int i =0; i<new_words; i++)
{
if (strcmp(string, dictionary[i]->word)==0)
return 0;
}
return 1;
}
int which_word(element ** dictionary, char * string)
{
for (int i =0; i<new_words; i++)
{
if (strcmp(string, dictionary[i]->word)==0)
return i;
}
return 0;
}
int main()
{
FILE * fp;
char word[30];
fp=fopen("input.txt", "r");
if (fp==NULL)
{
printf("FILE ERROR");
return 0;
}
while(!feof(fp))
{
fscanf(fp, "%s",word);
nwords++;
}
nwords--;
rewind(fp);
struct element * dictionary = (element*)malloc(sizeof(element)*nwords);
for (int i =0; i<nwords; i ++)
{
fscanf(fp, "%s", word);
if( is_word_new(&dictionary, word) )
{
strcpy(dictionary[new_words].word, word);
//dictionary[new_words].word= word;
dictionary[new_words].how_many=1;
new_words++;
}
else
dictionary[which_word(&dictionary, word)].how_many++;
word[0]='\0';
}
printf("\n\nFinal dictionary\n with %d words", new_words);
for (int i =0; i<new_words; i++)
{
printf("%s %d \n", dictionary[i].word, dictionary[i].how_many);
}
free(dictionary);
fclose(fp);
return 0;
}
the idea is that i first count how many words are in the text (which somehow is always greater by one than in fact). The function is_word_new checks if a newly read word is already in the dictionary. which_word() tells which word was found
However I get a segmentation fault running this program.
When I used the line which is commented // dictionary[i].word=word the program behaved as if there was only "word" in the dictionary.
Please give me hints where am I doing this stuff wrong
Must read question: Why is “while ( !feof (file) )” always wrong? Thanks to Jonathan Leffler's comment.
Please check my comments in the code below. I got you a start up for when the words are appearing once. I am letting the rest of the job for you, so that we can share the fun, but you can of course ask.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int new_words = 0;
int nwords = 0;
typedef struct element {
char word[30];
int how_many;
} element;
// no need to pass double pointer
int is_word_new(element* dictionary, char * string) {
int i;
for (i = 0; i < new_words; i++) {
printf("|%s|, |%s|\n", string, dictionary[i].word);
if (strcmp(string, dictionary[i].word) == 0)
return 0;
printf("i=%d\n",i);
}
return 1;
}
int which_word(element ** dictionary, char * string) {
int i;
for (i = 0; i < new_words; i++) {
if (strcmp(string, dictionary[i]->word) == 0)
return i;
}
return 0;
}
int main() {
FILE * fp;
char word[30];
fp = fopen("test.txt", "r");
if (fp == NULL) {
printf("FILE ERROR");
return 0;
}
printf("file read\n");
int read_counter;
while (!feof(fp)) {
read_counter = fscanf(fp, "%s", word);
// increment only if we really read something
if(read_counter >= 0)
nwords++;
}
// this is wrong, remove it
//nwords--;
rewind(fp);
printf("nwords = %d\n", nwords);
// do not cast what malloc returns. Also struct is not needed.
element * dictionary = malloc(sizeof (element) * nwords);
int i;
for (i = 0; i < nwords; i++) {
fscanf(fp, "%s", word);
printf("read |%s|\n", word);
if (is_word_new(dictionary, word)) {
strcpy(dictionary[new_words].word, word);
//dictionary[new_words].word= word;
dictionary[new_words].how_many = 1;
new_words++;
} else {
printf("bhka\n");
dictionary[which_word(&dictionary, word)].how_many++;
}
//word[0] = '\0';
}
printf("\n\nFinal dictionary\n with %d words", new_words);
for (i = 0; i < new_words; i++) {
printf("%s %d \n", dictionary[i].word, dictionary[i].how_many);
}
free(dictionary);
fclose(fp);
return 0;
}
Here is the test.txt I used:
sam klouvi george dit epfl
ok
end

Unexpected Segfault - What am I doing wrong

I've been trying to blow the cobwebs off my C programming skills, and I've been getting an error I can't seem to figure out. This program reads in a list of integers separated by newlines. This bit happens in read_integer_file... I have no issues going through the input there. It's when I pass the data back to main via out that I have the problem.
#include <stdlib.h>
#include <stdio.h>
int read_integer_file(char* filename, int* out)
{
FILE* file;
file = fopen(filename, "r");
/* check if the file open was successful */
if(file == NULL)
{
return 0;
}
int num_lines = 0;
/* first check how many lines there are in the file */
while(!feof(file))
{
fscanf(file, "%i\n");
num_lines++;
}
/* seek to the beginning of the file*/
rewind(file);
out = malloc(sizeof(int)*num_lines);
if(out == NULL)
return 0;
int inp = 0;
int i = 0;
while(!feof(file))
{
fscanf(file, "%i\n", &inp);
out[i] = inp;
printf("%i\n", out[i]); /* <---- Prints fine here! */
i++;
}
return num_lines;
}
int main(int argc, char** argv)
{
if(argc < 2)
{
printf("Not enough arguments!");
return -1;
}
/* get the input filename from the command line */
char* array_filename = argv[1];
int* numbers = NULL;
int number_count = read_integer_file(array_filename, numbers);
for(int i = 0; i < number_count; i++)
{
/* Segfault HERE */
printf("%i\n", numbers[i]);
}
}
You have not allocated any memory for numbers. Currently it is pointing to no where. When it gets back to the calling function it is still pointed to nowhere. Pass a pointer to a pointer to the function to allocate it within the function.
int read_integer_file(char* filename, int** out)
{
...
*out = malloc(sizeof(int)*num_lines);
...
int number_count = read_integer_file(array_filename, &numbers);
This is a version of your code working.. Keep in mind also that fscanf just skip the \n the way you wrote it so it's like writing fscanf(file, "%d");
And if you don't put a variable to handle what it reads the compiler may not see it but you'll probably get an error..
So here is the code :
#include <stdlib.h>
#include <stdio.h>
int read_integer_file(char* filename, int **out)
{
FILE* file;
file = fopen(filename, "r");
/* check if the file open was successful */
if(file == NULL)
{
return 0;
}
int num_lines = 0;
int garbi;
char garbc;
/* first check how many lines there are in the file */
while(!feof(file))
{
fscanf(file, "%d", &garbi);
fscanf(file, "%c", &garbc);
if (garbc=='\n') ++num_lines;
}
/* seek to the beginning of the file*/
rewind(file);
int *nbr = malloc(sizeof(int)*num_lines);
if(nbr == NULL)
return 0;
int i = 0;
while(!feof(file))
{
fscanf(file, "%d", &nbr[i++]);
fscanf(file, "%c", &garbc);
}
*out=nbr;
return num_lines;
}
int main(int argc, char** argv)
{
if(argc < 2)
{
printf("Not enough arguments!");
return -1;
}
/* get the input filename from the command line */
char* array_filename = argv[1];
int *numbers = NULL;
int number_count = read_integer_file(array_filename, &numbers);
int i;
for(i = 0; i < number_count; ++i)
printf("%d\n", numbers[i]);
return 0;
}

passing struct in function

I spend lot of time to pass a struct pointer in a function. everything in the code is working only I couldn't figure out how to pass a struct in a function then I can do some operation inside a function. can you explain where exactly i'm fail and how to fix it? Thanks.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int i=0;
int* i_ptr=&i;
int count(int q);
int line_count();
struct student {
int st_id;
char st_name[20];
int st_age;
char st_dep[7];
float st_grade;
};
int sort_student(struct student line[i],int i)
{
printf("%f",line[1].st_grade);
printf(" %s",line[1].st_name);
return 0;
}
int main()
{
/* struct loading from the file operation goes here */
int x=0;
int i=line_count();
struct student line[i];
char file_line[100];
char* line_parts;
FILE * fp;
if ((fp = fopen (file.txt", "r")) != NULL)
{
while (x<i) {
if(fgets(file_line,100,fp) != NULL); // gets line from the file.
{
line_parts = strtok(file_line,","); // breaks the line
line[x].st_id = atoi(line_parts); // conversition string to int
line_parts = strtok(NULL, ",");
strcpy(line[x].st_name,line_parts);
line_parts = strtok(NULL, ",");
line[x].st_age = atoi(line_parts);
line_parts = strtok(NULL, ",");
strcpy(line[x].st_dep,line_parts);
line_parts = strtok(NULL, ",");
line[x].st_grade = atoi(line_parts);
x++;
}
}
}
fclose(fp);
sort_student(&line[i],i);
return 0;
}
int line_count () //counts the number of line in the file, while loading the program.
{
FILE * fp; // file open from here.
int i=0;
int c;
if ((fp = fopen ("/Users/rishav/Desktop/try/try/file.txt", "r")) != NULL)
{
while ((c=fgetc(fp)) != EOF) {
if (c=='\n') {
i++;
}
}
fclose(fp);
}
else printf("file reading Error.\n");
return i;
}
int count(q) // keeps track of i
{
if(q==1)
{
(*i_ptr)++;
}
return *i_ptr;
}
You need to change your sort_student function definition to
int sort_student(struct student* line,int i) {
printf("%f",line->st_grade);
printf(" %s",line->st_name);
return 0;
}

Resources