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;
}
Related
i made this code for my college lesson:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
int palindromoR(int i, int f, char *s)
{
if (f - i <= 0)
return 1;
if (s[i] != s[f]) {
return 0;
} else {
return palindromoR(i+1, f-1, s);
}
}
void palindromo(char *s)
{
int saida = palindromoR(0, strlen(s) - 1, s);
if (saida)
{
printf("eh palindromo\n");
}
else
{
printf("nao eh palindromo\n");
}
}
void inversaR(char *str)
{
static int i=0;
int tam = strlen(str) - i;
char temp;
if (tam +1 == 0)
return;
temp = str[tam];
printf ("%c",temp);
i++;
return inversaR (str);
}
void inversa(char *s)
{
inversaR(s);
printf("\n");
}
unsigned long stirlingR(unsigned long n, unsigned long k)
{
// implemente essa função recursiva
return 0;
}
void stirling(int n, int k)
{
printf("%lu\n", stirlingR(n, k));
}
void padraoR(unsigned n)
{
}
void padrao(unsigned n)
{
padraoR(n);
printf("\n");
}
int main(int argc, char *argv[])
{
char file_name[MAX], aux[MAX];
FILE *entrada;
int t, a, b;
scanf("%s", file_name);
entrada = fopen(file_name, "r");
if (entrada == NULL)
{
printf("Nao encontrei o arquivo!");
exit(EXIT_FAILURE);
}
fscanf(entrada, "%d", &t);
if (t < 1 || t > 4)
{
printf("Parametros incorretos.\n");
printf("Ex:\n");
printf("tp01_recursao 1 [para testar palindromo]\n");
printf("tp01_recursao 2 [para testar inversa]\n");
printf("tp01_recursao 3 [para testar Stirling]\n");
printf("tp01_recursao 4 [para testar padrao]\n");
}
if (t == 1)
{
printf("\nTestando palindromo()\n\n");
fscanf(entrada, "%s", aux);
while (aux[0] != '.')
{
palindromo(aux);
fscanf(entrada, "%s", aux);
}
}
else if (t == 2)
{
printf("\nTestando inversa()\n\n");
fscanf(entrada, "%s", aux);
while (aux[0] != '.')
{
inversa(aux);
fscanf(entrada, "%s", aux);
}
}
else if (t == 3)
{
printf("\nTestando Stirling()\n\n");
fscanf(entrada, "%d %d", &a, &b);
while (a != -1)
{
stirling(a, b);
fscanf(entrada, "%d %d", &a, &b);
}
}
else if (t == 4)
{
printf("\nTestando padrao()\n\n");
fscanf(entrada, "%d", &a);
while (a != -1)
{
padrao(a);
fscanf(entrada, "%d", &a);
}
}
return 0;
}
My function inversaR seems to work when i try like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void inversaR(char *str)
{
static int i=0;
int tam = strlen(str) - i;
char temp;
if (tam +1 == 0)
return;
temp = str[tam];
printf ("%c",temp);
i++;
return inversaR (str);
}
void inversa(char *s)
{
inversaR(s);
printf("\n");
}
int main (){
char teste[100] = "alucard";
inversa(teste);
return 0;
}
the code above gives me the answer "dracula" as expected, but when trying with the first code it cuts the strings in 2 characters. The archive it's reading contains the following strings:
2
ab
gato
minerva
alucard
.
I tried to chance it using the function strrev() and it seems to work just fine, otherwise the same problem kept blowing my mind.
I tried out your code and saw the quirky chopped output you referred to. Doing some debugging of the code led me to the issue with your static variable, "i" in the recursive "inversaR" function. After each call with a different string, the value was left with an arbitrary value from the previous recursive call set which was giving either a partial string or no string at all.
With that it was apparent that when the final character had been printed and the return back up the function call stack was occurring, this variable needed to be reset. Following is a refactored version of the function.
void inversaR(char *str)
{
static int i=0;
int tam = strlen(str) - i;
char temp;
//printf("tam: %d\n", tam);
if (tam +1 == 0)
{
i = 0; /* This needs to be reset when returning up the recursive call stack */
return;
}
temp = str[tam];
printf ("%c",temp);
i++;
return inversaR (str);
}
Also, just to clarify to anyone testing this program, I added a "printf" statement prior to the prompt for a file name so that it is clear what is wanted for input.
printf("File name: "); /* Added to alert the user to enter a file name */
scanf("%s", file_name);
entrada = fopen(file_name, "r");
With those two bits of code refactored, and having created a text file with the sample string set, the following terminal output was created.
#Vera:~/C_Programs/Console/Dracula/bin/Release$ ./Dracula
File name: Test.txt
Testando inversa()
ba
otag
avrenim
dracula
All of the strings appear to have been properly reversed. Go ahead and try out these program tweaks and see if they meet the spirit of your project.
I am trying to store the values stored in a details.txt file into their appropriate place in a dynamically allocated struct. Am I doing something (that should be simple) incorrectly for this not to work? Is it necessary for me to use strtok and split by ','?
My details.txt reads:
mitch,8,1.78,burgers
murray,42,6.5,lasagna
travis,64,1.85,sushi
sam,12,1.94,bacon
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFFERSIZE 256
typedef struct
{
char name[BUFFERSIZE];
int favnumber;
float height;
char favfood[BUFFERSIZE];
} Person;
void print_person(Person *p)
{
printf("name: %s\n", p->name);
printf("num: %d\nheight: %.2f\nfav. food: %s\n\n",
p->favnumber, p->height, p->favfood);
}
int count_lines(FILE *fp)
{
int nlines = 0;
char c;
for (c = fgetc(fp); c != EOF; c = fgetc(fp))
{
if (c == '\n')
{
nlines++;
}
}
rewind(fp);
return nlines;
}
int main(void)
{
FILE *fp = fopen("details.txt", "r");
// count lines
int nlines = count_lines(fp);
printf("found %d lines\n\n",nlines);
Person *people = (Person*)malloc(nlines*sizeof(Person));
char buffer[BUFFERSIZE];
int i = 0;
while (fgets(buffer,BUFFERSIZE,fp) != NULL)
{
sscanf(buffer,"%s%d%f%s",people[i].name,
&(people[i].favnumber),
&(people[i].height),people[i].favfood);
print_person(&(people[i]));
i++;
}
printf("found %d people\n",i);
free(people);
fclose(fp);
}
Unfortunately, the current output of my program is:
found 4 lines
name: mitch,8,1.78,burgers
num: 0
height: 0.00
fav. food:
...
found 4 people
The problem is that the first %s parse the the whole line, and you need , in the format string to separate the fields. Not an issue here yet but I also used %[^,] for the last format string so it will not stop at the first space. Also added precision on the strings to avoid buffer overflows:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFFERSIZE 255
#define str(s) str2(s)
#define str2(s) #s
typedef struct
{
char name[BUFFERSIZE+1];
int favnumber;
float height;
char favfood[BUFFERSIZE+1];
} Person;
void print_person(Person *p)
{
printf("name: %s\n", p->name);
printf("num: %d\nheight: %.2f\nfav. food: %s\n\n",
p->favnumber, p->height, p->favfood);
}
int count_lines(FILE *fp)
{
int nlines = 0;
char c;
for (c = fgetc(fp); c != EOF; c = fgetc(fp))
{
if (c == '\n') {
nlines++;
}
}
rewind(fp);
return nlines;
}
int main(void)
{
FILE *fp = fopen("details.txt", "r");
// count lines
int nlines = count_lines(fp);
printf("found %d lines\n\n",nlines);
Person *people = (Person*)malloc(nlines*sizeof(Person));
char buffer[BUFFERSIZE+1];
int i = 0;
while (fgets(buffer,BUFFERSIZE+1,fp) != NULL)
{
// Changed line, see formatting of %s
sscanf(buffer,
"%" str(BUFFERSIZE) "[^,],%d,%f,%" str(BUFFERSSIZE) "[^,]",
people[i].name,
&(people[i].favnumber),
&(people[i].height),people[i].favfood);
print_person(&(people[i]));
i++;
}
printf("found %d people\n",i);
free(people);
fclose(fp);
}
I made program that helps with learning english. You have code below, but for my question you don't need to read and understand what's inside. What I want to do is to create .cfg or .ini file, that can be open with simple notepad and lets user modify:
MAX size (default is 15)
Sleep(x) value (default is 500)
I have no idea how can I make such config file that can be modified by user,link it with my c code, and then after runing program.exe it accepts changes from there. Any ideas?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <Windows.h>
#define MAX 15 //word max size
struct slowa
{
char pl_word[MAX];
char eng_word[MAX];
};
void menu(void);
int count_lines(FILE*);
void print_array1 (const int[],int); //print 1-dimension array
void swap (int*,int*);
int main ()
{
srand( time( NULL ) );
int i,k,j;
FILE* fp;
fp = fopen ("tekst", "r");
if (!fp)
{
printf ("zjebales"); //"you fucked up"
return -1;
}
const int lines = count_lines(fp);
int tab[lines]= {};
int* temp = (int*)malloc(lines*sizeof(int));
for (j=0; j<lines; j++)
{
temp[j]=j+1;
}
j=lines;
for (i=0; i<lines; i++)
{
k=rand()%j--;
tab[i]=temp[k]-1;
swap(temp+k,temp+j);
}
free(temp);
struct slowa arr[lines];
rewind (fp);
for (i=0; i<lines; i++)
{
fscanf(fp, "%s %s", arr[tab[i]].pl_word, arr[tab[i]].eng_word);
}
fclose(fp);
char text[MAX];
k=0;
system("cls");
menu();
scanf("%d",&j);
system("cls");
char ch;
while ((ch = getchar()) != '\n' && ch != EOF);
switch (j)
{
case 1:
for (i=0; i<lines; i++)
{
printf ("Podaj tlumaczenie:%s\n", arr[i].eng_word); //"Write translation"
//fgets (text, MAX, stdin);
scanf ("%s",text);
if (strcmp(arr[i].pl_word, text) == 0)
{
puts ("DOBRZE!"); //"Correct!"
k++;
}
else puts ("ZLE!"); //"Wrong"
Sleep(500);
system("cls");
}
break;
case 2:
for (i=0; i<lines; i++)
{
printf ("Podaj tlumaczenie:%s\n", arr[i].pl_word); //"Write translation"
scanf ("%s",text);
if (strcmp(arr[i].eng_word, text) == 0)
{
puts ("DOBRZE!"); //Correct!
k++;
}
else puts ("ZLE!"); //Wrong!
Sleep(500);
system("cls");
}
break;
default:
puts ("miales podac 1 lub 2 dzbanie"); //"You should put 1 or 2"
getchar();
return -1;
}
printf ("Odpowiedziales dobrze na %d/%d pytan. ", k, lines); //"You answered correctly k/lines words"
if (k==lines) puts("No dobra cos tam umiesz");
else if(k>(lines/2)&&k<lines) puts ("Mogloby byc lepiej");
else puts ("Wracaj do nauki debilu");
while ((ch = getchar()) != '\n' && ch != EOF);
getchar();
return 0;
}
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)?
So I am trying to read in a file and store it into my data struct, but every time I run it it either reads in garbage data and my struct is filled with 0s. Any suggestions?
I have functions to check if the data is valid, because my struct cannot store data that it has already stored (e.g same port or vmn).
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
typedef struct DataType{
double timeOffset;
int vmn;
int port;
}Data;
void insertDataType(Data *Data, double timeOffset, int vmn, int port){
Data->timeOffset = timeOffset;
Data->vmn = vmn;
Data->port = port;
}
double returnTimeOffset(Data D){
assert(D.timeOffset != 0.0);
return D.timeOffset;
}
int returnVMN(Data D){
assert(D.vmn != 0);
return D.vmn;
}
int returnPort(Data D){
assert(D.port != 0);
return D.port;
}
bool vmnValid(Data *Data, int n, int vmn){
int i;
for(i = 0; i <= n; i++){
if(Data[i].vmn != 0){
if(Data[i].vmn == vmn){
printf("Invalid vmn %d: vmn already inserted \n", vmn);
return false;
}
}
}
return true;
}
bool timeValid(Data *Data, int n, double timeOffset){
int i;
for(i = 0; i <= n; i++){
if(Data[i].timeOffset != 0.0){
if(Data[i].timeOffset == timeOffset){
printf("Invalid timeOffset %2lf: timeOffset already used \n", timeOffset);
return false;
}
}
}
return true;
}
bool portValid(Data *Data, int n, int port){
int i;
for(i = 0; i <= n; i++){
if(Data[i].port != 0){
if(Data[i].port == port){
printf("Invalid port %d: port already in use\n", port);
return false;
}
}
}
return true;
}
int main(int argc, const char * argv[]){
int n = 0;
int i = 0;
char c;
FILE *file;
// Open file
file = fopen("connect1.in", "r");
if (file == NULL) {
fprintf(stderr, "Invalid input file \n");
exit(1);
}
// Get number of lines (n)
while((c = fgetc(file))!= EOF){
if(c == '\n'){
n++;
}
}
printf("n = %d \n", n);
// Create a strut DataType of size n
Data *storage;
storage = calloc(n, sizeof(struct DataType));
// Read and insert the data
double timeOffset;
int vmn;
int port;
printf("\n");
while(fscanf(file, "%lf,%d,%d,", &timeOffset, &vmn, &port != EOF)){
printf("%lf %d %d \n", timeOffset, vmn, port);
if(timeValid(storage, n, timeOffset)){
if(vmnValid(storage, n, vmn)){
if(portValid(storage, n, port)){
insertDataType(&storage[vmn], timeOffset, vmn, port);
}
}
}
}
printf("\n");
printf("\n");
printf("Storage:\n");
for(i = 0; i <= n; i++){
printf("%3d: %2lf %d %d \n", i, storage[i].timeOffset, storage[i].vmn, storage[i].port);
}
}
After counting the number of lines the file pointer must be reset to the start of the file again.
Use the rewind() call which resets the file position back to file start after the line counting loop:
rewind(file);
Change
// while(fscanf(file, "%lf,%d,%d,", &timeOffset, &vmn, &port != EOF)){
while(fscanf(file, "%lf,%d,%d,", &timeOffset, &vmn, &port) != EOF){
// or better
while (fscanf(file, "%lf,%d,%d,", &timeOffset, &vmn, &port) == 3) {
#suspectus is correct, add rewind(file);
// change
// char c;
int c;
Minor considerations:
Data *storage;
// storage = calloc(n, sizeof(struct DataType));
// I like the style
storage = calloc(n, sizeof(*storage));
// In a number of places, function do not change *Data, so use `const`
// Useful to now, at a glance, that *Data is unchanged
// and forces the compiler to warn otherwise.
// bool vmnValid(Data *Data, int n, int vmn){
bool vmnValid(const Data *Data, int n, int vmn) {