How to save to file? - c

I've got a problem with my project. I don't know how to add an option which will save to file the result's from console. I think i shoud use fprintf but nothing works. Please help ;D
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct symbole
{
int symbol;
int czestosc;
};
struct symbole nowy[256];
void odczytIwyznaczenie(void);
void wyswietl(struct symbole nowy[]);
void sortuj(struct symbole nowy[]);
int main()
{
odczytIwyznaczenie();
sortuj(nowy);
wyswietl(nowy);
getchar();
return 0;
}
void odczytIwyznaczenie (void)
{
FILE *plik;
char n;
int i;
for (i=0; i<256; i++)
{
nowy[i].czestosc=0;
nowy[i].symbol=i;
}
plik = fopen("plik.txt","r");
if (plik == NULL)
{
printf("Blad odczytu!");
getchar();
exit(1);
}
while (n != EOF)
{
n = fgetc(plik);
for(i=0; i<256; i++)
{
if (nowy[i].symbol == n)
{
nowy[i].czestosc++;
break;
}
}
}
fclose (plik);
}
void sortuj(struct symbole nowy[])
{
int i, j, temp, temp1;
for (i = (256); i > 0; i--)
{
for (j = 1; j <= i; j++)
{
if (nowy[j-1].czestosc < nowy[j].czestosc)
{
temp = nowy[j-1].czestosc;
temp1=nowy[j-1].symbol;
nowy[j-1].czestosc = nowy[j].czestosc;
nowy[j-1].symbol=nowy[j].symbol;
nowy[j].czestosc = temp;
nowy[j].symbol=temp1;
}
}
}
}
void wyswietl(struct symbole nowy[])
{
int i;
for (i=0; i<256; i++)
{
if (nowy[i].czestosc!= 0)
printf ("%5d| %5c| %5d\n", nowy[i].symbol, nowy[i].symbol, nowy[i].czestosc);
}
}

You indeed need fprintf(), use it as follows
void wyswietl(struct symbole nowy[])
{
FILE *output;
int i;
output = fopen("OuptputFile.txt", "w");
if (output == NULL) /* maybe you don't have permission to create the file */
return;
for (i = 0 ; i < 256 ; i++)
{
if (nowy[i].czestosc == 0)
continue;
fprintf(output, "%5d| %5c| %5d\n", nowy[i].symbol,
nowy[i].symbol, nowy[i].czestosc);
}
}
Also, you have to initialize n before comparing it to EOF, change
while (n != EOF)
which is reached before n is initialized, to
while ((n = fgetc(pilk)) != EOF)

Related

Why do i have a segmentation fault (core dump) with big multidimensional array?

I have this simple program which has to receive in input a matrix[d][d] with every element separated by a , whenever is given the input AddM, then it is supposed to print the matrix.
It works well when the d is small, let's say around 20, but if I enter a larger d then it gives me a segmentation fault (core dump) error.
Can somebody explain why it has this behaviour?
Thank you for your time and sorry if my question is stupid.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LENGHT 5
int menu(char c[]);
int **buildAdjMat(int **m);
int d;
int main() {
char *command;
int m_result = 1;
int i = 0, j = 0;
int **m;
if (scanf("%d", &d) == 0)
return 0;
printf("d: %d\n", d);
m = (int **)malloc(d * sizeof(int *));
for (i = 0; i < d; i++) {
m[i] = (int *)malloc(d * sizeof(int));
}
do {
command = (char*)malloc(sizeof(char) * MAX_LENGHT);
if (scanf("%s", command) == 0)
return 0;
m_result = menu(command);
if (m_result == 1) {
m = buildAdjMat(m);
for (i = 0; i < d; i++) {
for (j = 0; j < d; j++) {
printf("%d ", m[i][j]);
}
printf("\n");
}
free(command);
} else {
printf("End! with value %d", m_result);
free(command);
}
} while(m_result == 1);
free(m);
return 0;
}
int menu(char c[]) {
if (strcmp(c, "AddM") == 0) {
printf("AddM!\n");
return 1;
} else {
return -1;
}
}
int **buildAdjMat(int **m) {
int i = 0, j = 0;
char c = '\0';
for (i = 0; i < d; i++) {
for (j = 0; j < d; j++) {
if (scanf("%d", &m[i][j]) == 0)
return NULL;
if (scanf("%c", &c) == 0)
return NULL;
}
}
return m;
}

Incorrect output using strcmp

I'm doing the day 8 of the 30 days of code in HackerRank and I am having a problem with strcmp.
The code asks the user for names of people and their numbers, then asks for other names, if a name wasn't entered before, then it outputs Not found, but if it was then it outputs the name and his number. But for some reason, the output only works in the last loop of the for statement.
Code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
typedef struct {
char name[100];
int number;
} phonebook;
int main() {
int n = 0;
do {
scanf("%i", &n);
} while (n < 1 || n > 100000);
int i = 0;
phonebook people[n];
for (i = 0; i < n; i++) {
scanf("%s %i", people[i].name, &people[i].number);
}
char othernames[n][100];
for (i = 0; i < n; i++) {
scanf("%s", othernames[i]);
}
for (i = 0; i < n; i++) {
if (strcmp(othernames[i], people[i].name) == 0) {
printf("%s=%i\n", people[i].name, people[i].number);
} else {
printf("Not found\n");
}
}
return 0;
}
You didn't find the othernames from the beginning to end to compare peopleevery time, so you need to replace
for (i = 0; i < n; i++) {
if (strcmp(othernames[i], people[i].name) == 0) {
printf("%s=%i\n", people[i].name, people[i].number);
}
else {
printf("Not found\n");
}
}
to
bool found = false;
for (i = 0; i < n; i++) {
for ( j = 0 ; j < n ; j++ ) {
if (strcmp(othernames[j], people[i].name) == 0) {
printf("%s=%i\n", people[i].name, people[i].number);
found = true;
}
}
}
if ( found == false ) printf("Not found\n");
The problem is othernames should just be an array of char, not a matrix. And for each othername entered, you must scan whole phonebook to find it or display Not found. As coded, you only test if the i-th othername typed happens to correspond to the i-th entry in the phone book.
Here is a modified version:
#include <stdio.h>
#include <string.h>
typedef struct {
char name[100];
int number;
} phonebook;
int main() {
int n = 0;
do {
if (scanf("%i", &n) != 1)
return 1;
} while (n < 1 || n > 100000);
phonebook people[n];
for (int i = 0; i < n; i++) {
if (scanf("%99s %i", people[i].name, &people[i].number) != 2)
return 1;
}
for (int i = 0; i < n; i++) {
char othername[100];
if (scanf("%99s", othername) != 1)
break;
int j;
for (j = 0; j < n; j++) {
if (strcmp(othername, people[j].name) == 0) {
printf("%s=%i\n", people[i].name, people[i].number);
break;
}
}
if (j == n) {
printf("Not found\n");
}
}
return 0;
}
Note that it is probably not a good idea to store phone numbers as int values. Better use a char array so an initial 0 is significant and to store longer numbers.

Print lines longer than 80 characters in C

I am not sure why wont this work.I am trying to print lines(from input) that are longer than 80 characters.But i dont get correct characters at all.I am not sure what am i doing wrong.Anyone there knows ??
Note: I dont want you to write me the whole new program doing this function (printing lines that are longer than 80).I just wanna know the wrong side of my program.Correction
Note:Last line overwrites the previous ones.
#include <stdio.h>
#define MAXARRAYSIZE 500
char c;
int i = 0;
int j = 0;
int jCopy = 0;
char line[MAXARRAYSIZE];
char linesToPrint[MAXARRAYSIZE][MAXARRAYSIZE];
void emptyArray(char theArray[]);
void InsertArrayIntoArray(char to[MAXARRAYSIZE][MAXARRAYSIZE], char from[], int toIndex, int lengthSoFar);
void printArray(char theArray[MAXARRAYSIZE][MAXARRAYSIZE], int lengthSoFarX);
int main(void) {
while ((c = getchar()) != EOF) {
if (i > MAXARRAYSIZE) {
i = 0;
}
if (j > MAXARRAYSIZE) {
j = 0;
}
if (c != '\n') {
line[i] = c;
i++;
//printf("%d",i);
} else {
printf("\n j:%d \n i:%d", j, i);
j++;
jCopy = j;
if (i >= 10) {
InsertArrayIntoArray(linesToPrint, line, j, i);
//printArray(linesToPrint, j, i);
}
emptyArray(line);
i = 0;
}
}
printArray(linesToPrint, jCopy);
}
void emptyArray(char theArray[]) {
int i;
for (i = 0; i < sizeof(theArray) / sizeof(theArray[0]); i++) {
theArray[i] = 0;
}
}
void InsertArrayIntoArray(char to[MAXARRAYSIZE][MAXARRAYSIZE], char which[], int toSize, int whichSize) {
int i, j;
//printf("\n To size: %d \t Which Size: %d",toSize,whichSize);
for (i = 0; i < toSize; i++) {
for (j = 0; j < whichSize; j++) {
to[i][j] = which[j];
}
}
}
void printArray(char theArray[MAXARRAYSIZE][MAXARRAYSIZE], int lengthSoFarX) {
int i, j;
for (i = 0; i < lengthSoFarX; i++) {
printf("\n Line %d :", i + 1);
printf(" %s\n", theArray[i]);
}
}
First of all the sizeof(theArray) cannot be taken because theArray is pointer as Joachim Pileborg pointed out.And the second mistake is in InsertArrayIntoArray function.
It should be like this :
void InsertArrayIntoArray(char to[MAXARRAYSIZE][MAXARRAYSIZE], char which[], int toSize, int whichSize) {
int i, j;
//printf("\n To size: %d \t Which Size: %d", toSize, whichSize);
for (j = 0; j < whichSize; j++) {
to[toSize][j] = which[j];
}
}

Duplicate Elimination in C

I am trying to do duplicate elimination from clients.txt (which has 7 names and surnames, some of them are repeated). In the end of file it writes the output to output.dat file. I did not get any error during the compiling but when i try to run it, it gives "003.exe stopped working" error. (003.c is C project name)
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct names
{
char name[25];
char surname[25];
};
int main()
{
int i, j;
char a[1] = {""};
struct names name[200];
FILE *file;
FILE *file2;
file = fopen("clients.txt", "r");
if (ferror(file))
{
printf ("File could not be opened");
}
while (fscanf(file, "%s", a) == 2)
{
i = 0;
fscanf(file, "%s %s", name[i].name, name[i].surname);
i++;
}
for (i = 0; i < 200; i++)
{
for (j = 0; j < 200; j++)
{
if (i != j && strcmp(name[i].name, name[j].name) == 0 && strcmp(name[i].surname, name[j].surname) == 0 )
{
strcpy(name[j].name, a);
strcpy(name[j].surname, a);
}
}
}
fclose(file);
file2 = fopen("output.dat", "w");
{
for (i = 0; i < 200; i++)
{
if ( strcmp(name[i].name, "") == 1 )
{
fprintf(file, "%s %s\n", name[i].name, name[i].surname);
}
}
}
fclose(file2);
system("pause");
return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct names {
char name[25];
char surname[25];
};
int isEqual(struct names *a, struct names *b){
return strcmp(a->name, b->name) == 0 && strcmp(a->surname, b->surname)==0;
}
int main(){
int i, j;
struct names name[200], a;
FILE *file;
file = fopen("clients.txt", "r");
if (!file){//ferror can't use to fopen
printf ("File could not be opened");
return -1;
}
i=0;
while (fscanf(file, "%24s %24s", a.name, a.surname) == 2){
int dup = 0;
for(j=0; j < i ;++j){
if(dup=isEqual(&a, &name[j]))
break;
}
if(!dup)//!dup && i<200
name[i++] = a;
}
fclose(file);
file = fopen("output.dat", "w");
for (j = 0; j < i; ++j){
fprintf(file, "%s %s\n", name[j].name, name[j].surname);
}
fclose(file);
system("pause");
return 0;
}

Segmentation fault when using I/O redirection to input a data set

Source:
#include<stdio.h>
int load(char fileName[], int array[]);
int sort(int array[], int length);
int print(int length, int array[]);
int main() {
char fileName[300];
int numList[300];
int length;
printf("File Name: ");
scanf("%s", fileName);
length = print(sort(numList,load(fileName, numList)), numList);
printf("\nLength: %i\n", length);
printf("Finished execution.\n");
return 0;
}
int load(char fileName[], int array[]) {
FILE *input = fopen(fileName, "r");
int length = 0, i = 0;
if(input == NULL) {
fprintf(stderr, "Error accessing file.\n");
} else {
while(fscanf(input, "%i", &array[i]) != EOF) {
i++;
length++;
}
}
fclose(input);
return length;
}
int sort(int array[], int length) {
int a, b, c;
for (a = 0 ; a < ( length - 1 ); a++) {
for (b = 0 ; b < length - a - 1; b++) {
if (array[b] > array[b+1]) {
c = array[b];
array[b] = array[b+1];
array[b+1] = c;
}
}
}
return length;
}
int print(int length, int array[]) {
int i;
printf("\n[NUMBERS]\n\n");
for (i = 0; i< length; i++) {
printf("[N]%i\n", array[i]);
}
return length;
}
I am required to use I/O redirection to submit a random data set of integers to the program, but when I use redirection to submit the file containing the data set, it throws a segfault. I am very familiar with segfaults and why they are traditionally thrown, but I've been sitting in front of this program for hours now with no progress on identifying where the issue stems from.
Here are some proposed changes, to make your code read from stdin instead of from a named file, which is what you say is needed:
int main() {
//char fileName[300];
int numList[300];
int length;
//printf("File Name: ");
//scanf("%s", fileName);
length = print(sort(numList,load(stdin, numList)), numList);
printf("\nLength: %i\n", length);
printf("Finished execution.\n");
return 0;
}
int load(FILE* input, int array[]) {
//FILE *input = fopen(fileName, "r");
int length = 0, i = 0;
if(input == NULL) {
fprintf(stderr, "Error accessing file.\n");
} else {
while(fscanf(input, "%i", &array[i]) != EOF) {
i++;
length++;
}
}
//fclose(input);
return length;
}
int sort(int array[], int length) {
int a, b, c;
for (a = 0 ; a < ( length - 1 ); a++) {
for (b = 0 ; b < length - a - 1; b++) {
if (array[b] > array[b+1]) {
c = array[b];
array[b] = array[b+1];
array[b+1] = c;
}
}
}
return length;
}
You need to update the load() proto near to top to:int load(FILE* input, int array[]);

Resources