I have a question on logical error, the error was
"Run-Time Check Failure #2 - Stack around the variable 'list' was corrupted."
there are a total of 60 lines in the in.txt file
this is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILE_NAME 20
#define LIST_SIZE 50
//void getData(RECORD name[], RECORD score)
typedef struct
{
char *name;
int score;
}RECORD;
int main (void)
{
// Declarations
FILE *fp;
char fileName[FILE_NAME];
RECORD list[LIST_SIZE];
char buffer[100];
int count = 0;
int i;
// Statements
printf("Enter the file name: ");
gets(fileName);
fp = fopen(fileName, "r");
if(fp == NULL)
printf("Error cannot open the file!\n");
while(fgets(buffer, 100, fp) != NULL)
{
list[count].name = (char*) calloc(strlen(buffer), sizeof(RECORD*));
if(count > 50)
{
}
if( count < 50)
{
sscanf(buffer,"%[^,], %d", list[count].name, &list[count].score);
for( i =1; i < (50 - count); i++)
{
list[count + i].name = 0;
list[count + i].score = 0;
}
}
count++;
}
printf("Read in %d data records\n", count);
fclose(fp);
return 0;
}
in this program I' m trying to read data from file to array of structures, so if the number of data is less than 50, structures that don't have data will be zero out and if the number of data is more than 50 the program will only read the first 50 structures.
how can i fix the runtime error?
Perhaps...
while(fgets(buffer, 100, fp) != NULL)
{
if( count >= 50)
{
break;
}
if( count < 50)
{
list[count].name = (char*) malloc(strlen(buffer)*sizeof(char));
sscanf(buffer,"%[^,], %d", list[count].name, &list[count].score);
count++;
}
}
for( i =0; i < (50 - count); i++)
{
list[count + i].name = 0;
list[count + i].score = 0;
}
What if count = 50?
Try with the following in your while loop bringing if block in the start or at the end;
if(count >= 50) //count should be checked for >= 50 before being used.
{
}
list[count].name = (char*) calloc(strlen(buffer), sizeof(RECORD*)); //list size is 50 so list[50] won't work. out of bound.
Related
I am new to C programming and I am getting a THREAD 1: EXC_BAD_ACCESS(code = 1, address 0x68)
when I run my program. The purpose of my code is to read from a txt file that contains positive and negative numbers and do something with it.
#include <stdio.h>
int main (int argc, const char * argv[]) {
FILE *file = fopen("data.txt", "r");
int array[100];
int i = 0;
int num;
while( fscanf(file, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[i] = num;
printf("%d", array[i]);
i++;
}
fclose(file);
for(int j = 0; j < sizeof(array); j++){
printf("%d", array[j]);
}
}
After
FILE *file = fopen("data.txt", "r");
Say
if(file == 0) {
perror("fopen");
exit(1);
}
Just a guess, the rest of the code looks ok, so likely this is the problem.
Also worth noting that you might have more than 100 numbers in your file, in which case you will blow past the size of your array. Try replacing the while loop with this code:
for (int i = 0; i < 100 && ( fscanf(file, "%d" , &num) == 1); ++i)
{
array[i] = num;
printf("%d", array[i]);
}
Do you have the file "data.txt" created and local?
touch data.txt
echo 111 222 333 444 555 > data.txt
Check that your file open succeeded.
Here is a working version,
#include <stdio.h>
#include <stdlib.h> //for exit
int main (int argc, const char * argv[])
{
FILE *fh; //reminder that you have a file handle, not a file name
if( ! (fh= fopen("data.txt", "r") ) )
{
printf("open %s failed\n", "data.txt"); exit(1);
}
int array[100];
int idx = 0; //never use 'i', too hard to find
int num;
while( fscanf(fh, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[idx] = num;
printf("%d,", array[idx]);
idx++;
}
printf("\n");
fclose(fh);
//you only have idx numbers (0..idx-1)
int jdx;
for(jdx = 0; jdx<idx; jdx++)
{
printf("%d,", array[jdx]);
}
printf("\n");
}
So i have een solving a problem where i have to find the prime numbers from the input file and save those prime numbers in an output file called output.txt.But If there are no prime numbers in the input file, i'll have to write “No prime numbers found” in the output file.So when i completed the code when there is no prime number it shows No prime numbers found 5-6 times and i only want it to appear 1 time.What is my mistake here?I am totally a noob here
#include <stdio.h>
#include <stdlib.h>
int Primecheck(const int number);
int main()
{
FILE* Number,
* Prime_N;
int num;
char sentence[50] = "No prime numbers found";
int length = strlen(sentence);
int i;
Number = fopen("input.txt", "r");
Prime_N = fopen("output.txt", "w");
if (Number == NULL || Prime_N == NULL)
{
printf("Unable to open file.\n");
exit(EXIT_FAILURE);
}
printf("File opened and Reading Done \n\n");
while (fscanf(Number, "%d", &num) != -1)
{
if (Primecheck(num) == 1)
fprintf(Prime_N, "%d\n", num);
else
for (i = 0; i < length; i++)
{
fputc(sentence[i], Prime_N);
}
}
fclose(Number);
fclose(Prime_N);
printf("Overwrite Success.");
return 0;
}
int Primecheck(const int number)
{
int i;
if (number < 0)
return 0;
for (i = 2; i <= number / 2; i++)
{
if (number % i == 0)
{
return 0;
}
}
return 1;
}
instead of
else
for(i=0;i<length;i++)
{
fputc(sentence[i] ,Prime_N);
}
you can just write
else
printf("No prime numbers found");
Well , as I see from your code , each time you read a number from the file you check if prime write it or write sentence . so of course you get multiple output ,
you should write the number to char* then check if changed after reading from Number and checking if prime write the number in the char* after the loop just check if the length of the char* that you stored the primes in it if changed write it else write your sentence ... Done
something like this
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
typedef struct {
char* data;
size_t size;
size_t capacity;
} string;
void init_string(string* s, size_t size){
s->data = (char*)malloc(sizeof(char) * size);
s->capacity = size;
s->size = 0;
}
void append(string* s,const char* str){
if(s->capacity - s->size < strlen(str)){
s->data = (char*)realloc(s->data, sizeof(char)* 4 * strlen(str));
}strcat(s->data, str);
}
void free_string(string* s){
free(s->data);
}
int is_odd(int n){
return n%2;
}
int main(){
int num[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
string str;
init_string(&str,1);
char* snum;
for(int i=0; i<18; i++){
if(!is_odd(i)){
sprintf(snum,"%d",num[i]);
append(&str, snum);
append(&str, "\n");
}
//printf(snum);
//strcat(str, snum);
}
printf("%s",str.data);
free_string(&str);
//printf(str);
return 0;
}
I am trying to rewrite text in files, changing first line by +1(that holds number of struct saved in igraci.txt) This part is working fine. Then rewrite all text that was there before(This is also working fine) and in the end add 2 new lines in text. Problem is in the last code i wrote here
These are some global variables that I am having problem with and strcture
int RijeciBroj = 0;
int IgraciBroj = 0;
typedef struct Igrac
{
char ime[20];
int brojPoena;
};
This is method for allocating memmory for structures having in mind that one strcture is going to be added
struct Igrac* napraviProstor(int n) {
IgraciBroj = n; //here I try to give global new value
printf("U NAPRAVI PROSTOR : %d", IgraciBroj); // Here i get -9282928
return (struct Igrac*) malloc((n + 1) * sizeof(struct Igrac));
}
This is method that is reading text from file and storing it in allocated memory
void ucitajIgrace(struct Igrac *arr) {
static const char filename[] = "igraci.txt";
FILE *file;
file = fopen(filename, "r");
if (file != NULL)
{
char line[20];
int n;
fscanf(file, "%d", &n);
int i = -1;
int k = 0;
fgets(line, 20, file);
while (fgets(line, 20, file) != NULL) /* read a line */
{
line[strcspn(line, "\n")] = '\0';
i++;
if (i == 0) {
strcpy((arr + k)->ime, line);
}
if (i == 1) {
(arr + k)->brojPoena = atol(line);
k++;
i = -1;
}
}
printf("Igraca: %d", IgraciBroj); //here i get -9892827280
fclose(file);
}
else
{
perror(filename);
}
}
Main method
int main()
{
int o;
Igrac *igr;
FILE *file1;
file1 = fopen("igraci.txt", "r");
if (file1 != NULL)
{
char line[20];
fscanf(file1, "%d", &o); //first line is number of structs
igr = napraviProstor(o);
ucitajIgrace(igr);
}
pocniIgru(rijeci,igr); //ignore rijeci that is another array that is working perfect and has nothing to do with my problem
return 0;
}
This is method where I have problem
void pocniIgru(char** rijeci, struct Igrac *igraci) {
int dobijeni[5] = {}; //array that is saving random numbers so they don't repeat
int brojac1 = 0; //used for index of dobijeni[5]
char srpska[30]; // for user input
char ime[20]; //for users name that we are going to store in igraci.txt
int poeni = 0; //number of points
bool moze; //boolean for loop control
printf("Pocinje igra\n");
printf("\n\n\n\n");
int pitanje; // for random number that we are going to get
for (int i = 0; i < 5; i++) {
moze = true;
LOOP:do {
srand(time(NULL));
pitanje = rand() % RijeciBroj-1; //random number between 0 - global variable here global variable is working fine!
if (pitanje % 2 != 0) {
pitanje++; // I need even number and 0 is accepted
}
for (int k = 0; k < 5; k++) {
if (dobijeni[k] == pitanje) { //checking if we arleay had that number
goto LOOP; // goto LOOP if we had that number so we pick another
}
}
dobijeni[brojac1] = pitanje; //storing that number in loop for later check so it won't repeat
moze = false; // do-while stops
brojac1++;
} while (moze);
printf("Engleska rijec je: %s", rijeci[pitanje]); //get word from array
printf("Unesite rijec na srpskom jeziku: ");
scanf("%30s", srpska); //user input for comparing
strtok(rijeci[pitanje + 1], "\n"); //we need to remove newline
if (strcmp(rijeci[pitanje+1], srpska) == 0) { //cheking if next word is same with user input
poeni += 2;
printf("Tacno! Vas broj peona je %d\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", poeni);
}
else {
poeni -= 1;
if (brojac != 5) {
printf("Greska! Vas broj peona je %d\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", poeni);
}
}
}
printf("Ukupan broj poena je: %d\n", poeni);
printf("Unesite svoje ime: "); //Enter your name
scanf("%s", ime); //get name
if (strcmp(ime, "")) { //check if it's empty
IgraciBroj += 1; //global variable +1 for rewriting in file
strcpy((igraci + IgraciBroj)->ime, ime); //save name in char* struct in last place that is empty
(igraci + IgraciBroj)->brojPoena = poeni; //save points in char* struct in last place that is empty
printf("%s osvojili ste %d poena", (igraci + IgraciBroj)->ime, (igraci + IgraciBroj)->brojPoena); //Here i get normal result and name
FILE *file1;
file1 = fopen("igraci.txt", "w");
if (file1 != NULL)
{
fprintf(file1, "%d\n", IgraciBroj);
for (int broj = 0; broj < IgraciBroj; broj++) {
fprintf(file1, "%s\n", (igraci + broj)->ime); //Problem !! I get some lines before name in file example(----------Name)
fprintf(file1, "%d\n", (igraci + broj)->brojPoena); //Problem !! I get some number like -9899887
}
}
}
I'm trying to write a program which will read from text files and then output the minimum, maximum and average values. The trouble I am having is ignoring comments in the text files that begin with a hashtag. Here is my working code so far. Can anyone help?
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
char ch, filename[20];
FILE *lun;
int num, min, max, sum, count, first;
printf("Please enter the name of file to load:");
scanf ("%s", filename);
lun=fopen(filename, "r");
if ( lun != NULL)
{
for ( sum= count= first= 0; fscanf( lun, "%d", &num ) == 1; sum += num, ++count )
if ( !first ) { min= max= num; first= 1; }
else if ( num > max ) max= num;
else if ( num < min ) min= num;
fclose( lun );
printf( " Minimum value: %d\n Maximum value: %d\n Average value: %lf\n",
min, max, sum / (double) count );
}
else
printf( "Unable to read file.\n" );
return 0;
}
Read the data in lines (use fgets()).
If the line contains a #, terminate the string there by replacing the '#' with '\0'. Then scan the line for numbers.
See also How to use sscanf() in loops?
And don't forget to check that the file was opened.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char filename[20];
printf("Please enter the name of file to load: ");
if (scanf("%19s", filename) != 1)
{
fprintf(stderr, "Failed to read file name\n");
return 1;
}
FILE *lun = fopen(filename, "r");
if (lun == NULL)
{
fprintf(stderr, "Failed to open file %s for reading\n", filename);
return 1;
}
char line[4096];
int min = 0; // Avoid compilation warnings (may be used uninitialized)
int max = 0; // Ditto
int sum = 0;
int count = 0;
while (fgets(line, sizeof(line), lun) != NULL)
{
char *hash = strchr(line, '#');
if (hash != NULL)
*hash = '\0';
int pos;
int num;
int off = 0;
while (sscanf(line + off, "%d%n", &num, &pos) == 1)
{
if (count == 0)
min = max = num;
if (num > max)
max = num;
if (num < min)
min = num;
sum += num;
count++;
off += pos; // Skip through line
}
}
fclose(lun);
printf("Minimum value: %d\nMaximum value: %d\nAverage value: %lf\n",
min, max, sum / (double)count);
return 0;
}
If your compiler doesn't support C99 or later, you will have to move variable declarations to the start of a block (immediately after a {).
Handling doubles isn't really any harder:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char filename[20];
printf("Please enter the name of file to load: ");
if (scanf("%19s", filename) != 1)
{
fprintf(stderr, "Failed to read file name\n");
return 1;
}
FILE *lun = fopen(filename, "r");
if (lun == NULL)
{
fprintf(stderr, "Failed to open file %s for reading\n", filename);
return 1;
}
char line[4096];
double min = 0.0; // Avoids 'used when uninitialized' warnings
double max = 0.0; // Avoids 'used when uninitialized' warnings
double sum = 0;
int count = 0;
while (fgets(line, sizeof(line), lun) != NULL)
{
char *hash = strchr(line, '#');
if (hash != NULL)
*hash = '\0';
int pos;
double num;
int off = 0;
while (sscanf(line + off, "%lf%n", &num, &pos) == 1)
{
if (count == 0)
min = max = num;
if (num > max)
max = num;
if (num < min)
min = num;
sum += num;
count++;
off += pos; // Skip through line
}
}
fclose(lun);
printf("Minimum value: %f\nMaximum value: %f\nAverage value: %f\n",
min, max, sum / count);
return 0;
}
I am new to C programming and I am getting a THREAD 1: EXC_BAD_ACCESS(code = 1, address 0x68)
when I run my program. The purpose of my code is to read from a txt file that contains positive and negative numbers and do something with it.
#include <stdio.h>
int main (int argc, const char * argv[]) {
FILE *file = fopen("data.txt", "r");
int array[100];
int i = 0;
int num;
while( fscanf(file, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[i] = num;
printf("%d", array[i]);
i++;
}
fclose(file);
for(int j = 0; j < sizeof(array); j++){
printf("%d", array[j]);
}
}
After
FILE *file = fopen("data.txt", "r");
Say
if(file == 0) {
perror("fopen");
exit(1);
}
Just a guess, the rest of the code looks ok, so likely this is the problem.
Also worth noting that you might have more than 100 numbers in your file, in which case you will blow past the size of your array. Try replacing the while loop with this code:
for (int i = 0; i < 100 && ( fscanf(file, "%d" , &num) == 1); ++i)
{
array[i] = num;
printf("%d", array[i]);
}
Do you have the file "data.txt" created and local?
touch data.txt
echo 111 222 333 444 555 > data.txt
Check that your file open succeeded.
Here is a working version,
#include <stdio.h>
#include <stdlib.h> //for exit
int main (int argc, const char * argv[])
{
FILE *fh; //reminder that you have a file handle, not a file name
if( ! (fh= fopen("data.txt", "r") ) )
{
printf("open %s failed\n", "data.txt"); exit(1);
}
int array[100];
int idx = 0; //never use 'i', too hard to find
int num;
while( fscanf(fh, "%d" , &num) == 1) { // I RECEIVE THE ERROR HERE
array[idx] = num;
printf("%d,", array[idx]);
idx++;
}
printf("\n");
fclose(fh);
//you only have idx numbers (0..idx-1)
int jdx;
for(jdx = 0; jdx<idx; jdx++)
{
printf("%d,", array[jdx]);
}
printf("\n");
}