c fwrite() writing data only right one of the struct variable? - c

This function is supposed to get a parameter as the pointer of a file and put all file into the struct anagram, then write it to another file. Right now the data only contains
a.word, but it suppose to containst a.sorted too?
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include "anagrams.h"
void buildDB ( const char *const dbFilename )
{
FILE *dict, *anagramsFile;
struct anagram a;
//check if dict and anagram.data are open
errno=0;
dict= fopen(dbFilename, "r");
if(errno!=0) {
perror(dbFilename);
exit(1);
}
errno=0;
anagramsFile = fopen(anagramDB,"wb");
char word[SIZE];
char *pos;
int i=0;
while(fgets(word, SIZE, dict) !=NULL) {
//get ripe of the '\n'
pos=strchr(word, '\n');
*pos = '\0';
strncpy(a.word,word,sizeof(word));
//lowercase word
int j=0;
while (word[j]) {
tolower(word[j]);
j++;
}
/* sort array using qsort functions */
qsort(word,strlen(word), 1, charCompare);
strncpy(a.sorted,word,sizeof(word));
fwrite(&a,1,sizeof(word),anagramsFile);
i++;
}
fclose(dict);
fclose(anagramsFile);
}
data:

char word[SIZE];
...
fwrite(&a,1,sizeof(word),anagramsFile);
sizeof(word) returns the full size of the buffer, so you're writing the full length of the buffer each time. You'll want to use strlen() or similar to only write the part of the buffer you're actually using.

Related

Passing data from a two-dimensional array to a structure

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct words {
char *mas;
}words;
int main(void) {
FILE *fp=fopen("test.txt", "r");
char str[100];
char arr[100][100];
int k=0;
words_in->mas=malloc(sizeof(char)*sizeof(arr));
char *istr;
printf("\nFile text\n\n");
for (int i = 0; i < 3; i++) {
istr = fgets(str, 100, fp);
printf("%s", istr);
for (char* istr = strtok(str, " .\t\n"); istr; istr = strtok(NULL, " .\t\n")) {
strcpy(arr[k++], istr);
}
}
How do I pass all words written to the two-dimensional array to the structure?
I want my structure to have an array of char pointers, instead of just one pointer. Or a linked list of pointers. Or an array of structs.
And is it possible to somehow dynamically allocate memory for the structure and for arrays?
If you want to prevent two loops and you are ready to sacrifice some memory you can follow this approach
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
typedef struct words {
char **mas;
}words;
int main()
{
FILE *fp=fopen("test.txt", "r");
struct stat statbuf;
fstat(fileno(fp), &statbuf);
long f_size = statbuf.st_size;
words words_in;
words_in.mas = (char**) malloc(sizeof(char*) * f_size); // In worst case each byte is one word.
char fbuf[f_size+1]; // In worst case all bytes form one word ;
long word_count = 0;
while(fscanf(fp,"%s", fbuf) == 1) {
words_in.mas[word_count] = strdup(fbuf);
word_count++;
}
for (long i = 0; i < word_count; i++) {
printf("%s\n",words_in.mas[i]);
}
return 0;
}
INPUT 1
Apple
Bat
Cat
OUTPUT 1
Apple
Bat
Cat
INPUT 2
AppleBatCat
OUTPUT 2
AppleBatCat
INPUT 3
Apple Bat Cat
OUTPUT 3
Apple
Bat
Cat

How to read line by line using system call in C

In my program, I can currently read char by char a file with given name "fichier1.txt", but what I'm looking for is to store a line(line char pointer here) and then display it that way :
-ligne 1 : content line 1
-line 2 : content line 2
-ect...
I've tried to store char by char but since it's a pointer and I'm yet that much familiar with pointers I'm not able to store a line and then reuse the pointer to store the char of the next line.
I have to say that it's part of a school projet and I have to use POSIX standard.
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include <pthread.h>
#include<string.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
int read_fd, write_fd;
off_t offset = 0;
char lu;
struct stat statFd;
char *fichier = "fichier1.txt";
read_fd = open(fichier,O_RDONLY);
stat(fichier, &statFd);
if(read_fd == -1){
perror("open");
exit(EXIT_FAILURE);
}
int i = 0;
char * line; // variable to store line
while(lseek(read_fd,offset, SEEK_SET) < statFd.st_size)
{
if(read(read_fd, &lu, 1) != -1)
{
printf("%c",lu);
offset++;
} else {
perror("READ\n");
close(read_fd);
close(write_fd);
exit(EXIT_FAILURE);
}
}
return 0;
}
I'd like to use open() function and not fopen()
Since you are able to read character after character from the file, the logic in while loop will be used to store an entire line (up to 199 characters, you can increase it though) at once in an array & then display it:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(void)
{
FILE *fptr=fopen( "fichier1.txt","r");
int i;
char arr[200]; //THIS ARRAY WILL HOLD THE CONTENTS OF A LINE TEMPORARILY UNTIL IT IS PRINTED
int temp_index=0,line_number=1;;
memset(arr,'\0',sizeof(arr));
while((i=getc(fptr))!=EOF)
{
if(i!='\n')
{
arr[temp_index++]=i;
}
if(i=='\n')
{
printf(line %d: %s\n",line_number++,arr);
temp_index=0;
memset(arr,'\0',sizeof(arr));
}
}
return 0;
}
Calling lseek at every iteration may be inefficient and may fail on devices which are incapable of seeking. I would write a program along these lines below if I don't need to store lines.
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int lc = 0; /* line count */
int c; /* character read */
FILE *fp = fopen("fichier1.txt", "r");
if (fp == NULL) {
perror("fopen");
return EXIT_FAILURE;
}
while ((c = fgetc(fp)) != EOF) {
printf("line %d: ", ++lc);
while (c != '\n' && c != EOF) {
putchar(c);
c = fgetc(fp);
}
putchar('\n');
}
return 0;
}
Or, a program using fgets to read a line at once:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int main (void)
{
int lc = 0; /* line count */
char buf[4096]; /* buffer to store the line read */
bool newline = true;
FILE *fp = fopen("fichier1.txt", "r");
if (fp == NULL) {
perror("fopen");
return EXIT_FAILURE;
}
while (fgets(buf, sizeof buf, fp) != NULL) {
if (newline)
printf("line %d: ", ++lc);
printf("%s", buf);
newline = strchr(buf, '\n');
}
return 0;
}

returning permutes in a string in C

I need to write a function that returns every permute of a word in a given text file.
For some reason the output is wrong and I don't really understand why.
However, if instead of writing a function that should check a presnce of a letter (as seen below the function chars(char,char*))
I write the needed letters for check manually
it works as intended.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 100
void permute(FILE *fp, char *perm){
int c,i,perm_size=0;
int flag,chars(char,char *);
char permute[MAX];
i=0;
while(perm[i++])
perm_size++;
flag=0;
i=0;
while(!feof(fp)){
c=fgetc(fp);
if(chars(c,perm)==0){/*a function that checks c with each one of the permutes chars*/
flag++;
permute[i++]=c;
if (flag == perm_size){/*if the permute is the word's length*/
permute[i]='\0';
printf("%s\n",permute);
flag=0;
i=0;
permute[0]='\0';
}
}
else{
flag=0;
i=0;
}
}
}
int chars(char ch, char *str){
while(*str++)
{
if(ch==*str)
return 0;
}
return 1;
}
#include "func.h"
#include <string.h>
int main(int argc,char **argv){
FILE *fp;
char *input,*perm;
char *prog=argv[0];
void permute(FILE *, char *);
if(argc==1)
{
fprintf(stderr,"%s error: no arguments\n",prog);
exit(1);
}
input=argv[1];
perm=argv[2];
if(!(fp=fopen(input,"r")))
{
fprintf(stderr,"%s error: cannot open file\n",prog);
exit(1);
}
permute(fp,perm);
fclose(fp);
return 0;
}
input:
./program text chairs
output:
nothing
As told - you should really learn debuging your programs, so I did - I incremented wrongly a value in a function chars(char , char *)
a good pointer explanation from other user

File pointers led to core dump. Probably something stupid

Write the program myuniq.c that contains a function void process_file(FILE* f) that reads all input from the given file one line at the time while keeping two consecutive lines in memory, and prints each line to the standard output if it is not equal to the previously read line.
^^This is the assignment i'm working on. My code below is:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void process_file(FILE* f);
int main()
{
FILE *fil = fopen("text.txt","r");
process_file(fil);
return 0;
}
void process_file(FILE* f)
{
FILE *fi = f;
char *firstLine = fgets(firstLine, 999, f);
char *secondLine = fgets(secondLine, 999, f);
while (feof(fi))
{
if (firstLine == secondLine)
{
puts(secondLine);
}
else
{
puts(firstLine);
puts(secondLine);
}
firstLine++;
secondLine++;
}
}
It compiled fine...but on every run it says core dumped. I can't see where I went wrong? Any ideas?
You don't check the return value of fopen, you don't allocate any memory for the strings into which you read, you don't continue reading input from the file, you don't correctly check for the end of input.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MY_MAX_LINE 999
void process_file(FILE* f)
{
char firstLine[MY_MAX_LINE + 1];
char secondLine[MY_MAX_LINE + 1];
while (1)
{
if (!fgets(firstLine, sizeof(firstLine), f))
break;
puts(firstLine);
if (!fgets(secondLine, sizeof(secondLine), f))
break;
if (strncmp(firstLine, secondLine, sizeof(firstLine)))
puts(secondLine);
}
if (!feof(f))
perror("Problem reading from file"), exit(1);
}
int main(int argc, char **argv)
{
FILE *f = fopen("text.txt", "r");
if (!f)
perror("text.txt"), exit(1);
process_file(f);
fclose(f);
return 0;
}

Read From File and Store Strings into a Multidimensional Array of Strings in C

I really need to know how to fix this.
I have a file that is read and I store the strings from the file into an array that is passed as an argument, but I can't figure out how to make it work.
When I do print the content of the array it says null.
So how do I pass a multi-dimensional array of strings to readfiles() and make it save the strings in the array passed as parameter, each string in one position?
Thanks for the help.
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <strings.h>
#define max_chars_string 10000
#define n_strings 100
int main(int argc, char **argv)
{
char *filename;
char strings_hashes[n_strings][max_chars_string];
char * pointer_string = &strings_hashes[0][0];
int n_lines;
int i = 0;
filename = (char*)malloc(strlen(argv[1])*sizeof(char));
if(argc !=3){
fprintf(stderr, "Usage : %s [text_file] [cores]",argv[0]);
exit(0);
}
strcpy(filename,argv[1]);
read_lines(filename,pointer_string);
for(i = 0; i<n_lines;i++){
printf("%s \n",strings_hashes[i][max_chars_string]);
}
return 0;
}
void read_lines(char * filename, char *pointer){
FILE *fp;
char str[max_chars_string];
int i =0;
if((fp = fopen(filename, "r"))==NULL) {
printf("Cannot open file.\n");
exit(1);
}
while(!feof(fp)) {
while(fgets(str, sizeof str, fp)) {
strcpy(pointer, str);
printf("%s", str);
pointer++;
i++;
}
}
fclose(fp);
}
Change
void read_lines(char * filename, char *pointer){
to
void read_lines(char * filename, char (*pointer)[max_chars_string]){
(pointer's type needs to be "pointer to array of max_chars_string chars". When using pointers to access multidimensional arrays, the pointer type needs to know the all the dimensions except for the outermost one, so that it knows how far to skip along when incremented.)
Change
strcpy(pointer, str);
to
strcpy(*pointer, str);
Now call it as
read_lines(filename,strings_hashes);
(This is equivalent to the following, which may be clearer:)
read_lines(filename,&string_hashes[0]);
Finally, you want to print a string not an individual character, so use
printf("%s \n",strings_hashes[i]);

Resources