C program to put the output into a new file - c

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;
}

Related

Thread 1: EXC_BAD_ACCESS (code=1, address=0x68 [duplicate]

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");
}

read indefinite amount of integers and print on file

*this program read integers until one is negative then prints on a file a characteristic of each of them: how many integers it can be divided by. the problem is that it keeps asking for integers even when i inseert negative ones. please let me know if you can a way to fix this without changing too much of the code
#include <stdio.h>
#include <stdlib.h>
int checkdiv(int *n);
int main(int argc, char * argv[]){
int *p;
int i, j;
FILE *fp;
int amount;
i=0;
p=NULL;
if(fp = fopen("ris.txt", "w")){
do{i++;
p=realloc(p,sizeof(int)*i);
scanf("%d", (p+i-1));
amount=checkdiv(p+i-1);
if(amount!= -1);
fprintf(fp,"%d %d\n", *(p+i-1),amount);
}while(p+i-1>0);
}else{
printf("errore");
}
fclose(fp);
free(p);
return 0;
}
int checkdiv(int *n){
int i;
int amount=0;
for(i = 2;i < *n; i++){
if(*n % i == 0){
amount++;
}
}
if(*n <= 0){
amount= -1;
}
return amount;
}
Your problem is in:
}while(p+i-1>0);
must be;
}while(*(p+i-1)>0);
HTH
You should remove semi colon in line
if(amount!=-1);
so that the statement below it can be included in if block.

fscanf not reading from a file containing asterisk characters

I tried to read a file containing an empty box of '*', the error message doesn't get printed, so the file is opened, but the scan doesn't work. I tried to print the count variable, and the value of count is 0. I don't really know where the fault is. Please help... Thanks
the file content that I want to read
int openmap(int file_no){
char filename[32];
char mapp[100][100];
int number;
int count;
int x[100];
int nomor = 1;
for(int i = 1; i <= file_no; i++){
sprintf(filename, "map%d.txt", i);
FILE *test = fopen(filename,"r");
if(test)
{
printf("%2d. Map %d\n", nomor, i);
x[nomor-1] = i;
nomor++;
fclose(test);
}else if(!test && i > file_no){
printf("No map available!");
return 1;
}
}
do{
printf("[0 to cancel] [1 - %d]>> ", nomor-1);
scanf("%d", &number);
}while(number < 0 || number > file_no);
if(number > 0){
sprintf(filename,"map%d.txt", x[number-1]);
printf("%s", filename);
FILE *open = fopen(filename, "r");
if(!open){
printf("error");
}
while(!feof){
fscanf(open, "%[^\n]\n", mapp[count]);
count++;
}
fclose(open);
for(int i = 0; i < count ; i++){
printf("%s\n", mapp[i]);
}
}
}
I created a small test program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main () {
char mapp[100][100];
int i, count = 0;
char filename[32];
sprintf(filename, "test.txt");
FILE *open = fopen(filename, "r");
if(!open){
printf("error");
}
while(!feof(open)){
fscanf(open, "%[^\n]\n", mapp[count]);
count++;
}
fclose(open);
for(i = 0; i < count ; i++){
printf("%s\n", mapp[i]);
}
}
as far as i can see the only issue you have regarding the relevant section is your while loop condition, you should use: while(!feof(open)) - i tested my solution and it works so it seems that this is the only issue in your solution

Reading the result of a contest from a file and sort the name alphabetically with related score

i have to read from a file which contains names and scores the results of a contest but the function fscanf is not working properly.. Does it have to do with newlines or something?
I'll leave below the code and the screenshots of the issue i'm having.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct contest
{
char name[25];
int score;
}Contest;
int main(int argc, const char * argv[]) {
Contest players[100];
FILE *fp;
fp = fopen("contest.txt", "r");
if(fp == NULL)
{
fprintf(stderr, "Error: failed to open the file\n");
exit(EXIT_FAILURE);
}
int cnt = 0;
while(fscanf(fp, "%s %d", players[cnt].name, &players[cnt].score) != EOF)
{
++cnt;
}
char temp[25];
for(int t = 0; t < cnt; ++t)
{
for(int u = 0; u < cnt; ++u)
{
if(strcasecmp(players[t].name, players[u].name) > 0)
{
strcpy(temp, players[t].name);
strcpy(players[t].name, players[u].name);
strcpy(players[u].name, temp);
}
}
}
for(int t = 0; t < cnt; ++t)
{
fprintf(stdout, "Name : %s Score : %d\n", players[t].name, players[t].score);
}
fclose(fp);
return 0;
}
Input:
Randal  34
Leonel  67
Vaughn  100
Missy  68
Cristopher  92
Dagmar  102
Blondell  88
Milly  83
Darrel  12
Josh  71
Output:
You've just made two little mistakes: (1) forgot to also swap the scores and (2) did the wrong comparison in the strcasecmp. For the rest, it's all working fine here.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
typedef struct contest
{
char name[32];
int score;
} Contest;
int main()
{
Contest players[100];
FILE *fp = fopen("contest.txt", "r");
assert(fp);
int cnt = 0;
while(fscanf(fp, "%s %d", players[cnt].name, &players[cnt].score) != EOF)
++cnt;
for(int i = 0; i < cnt; ++i)
{
for(int j = 0; j < cnt; ++j)
{
if(strcasecmp(players[i].name, players[j].name) < 0)
{
int tempScore = players[i].score;
players[i].score = players[j].score;
players[j].score = tempScore;
char tempName[32];
strcpy(tempName, players[i].name);
strcpy(players[i].name, players[j].name);
strcpy(players[j].name, tempName);
}
}
}
for(int i = 0; i < cnt; ++i)
fprintf(stdout, "Name : %s Score : %d\n", players[i].name, players[i].score);
fclose(fp);
return 0;
}

Error when trying to read in numbers from txt file in C

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");
}

Resources