Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define MAX_LINE_LEN 10000
- #define MAX_NO_LINES 100
- /*
- * On success, the function returns str.
- If the end-of-file is encountered while attempting to read a character, the eof indicator is set (feof).
- If this happens before any characters could be read, the pointer returned is a null pointer (and the contents of str remain unchanged).
- If a read error occurs, the error indicator (ferror) is set and a null pointer is also returned (but the contents pointed by str may have changed).
- *
- */
- /*
- * void* malloc (size_t size);
- *
- *
- */
- typedef struct{
- char first_chars[100];
- int line_length;
- int no_characters;
- }LineInfo;
- int main() {
- FILE * f = fopen("../in.txt", "r");
- if (f == NULL)
- return 100;
- char **tab = (char **)malloc(sizeof(char*)*MAX_NO_LINES);
- char* linie = (char *)malloc(sizeof(char)* MAX_LINE_LEN);
- char* ok=linie;
- int n = 0;
- while (ok == linie){
- ok = fgets(linie, MAX_LINE_LEN, f);
- if(ok != linie)
- break;
- tab[n] = (char*)malloc(sizeof(char) * (strlen(linie) + 1));
- strcpy(tab[n], linie);
- n++;
- }
- free(linie);
- fclose(f);
- //************************************************** AICI AM CONTINUTUL IN MEMORIE ************//
- FILE * fout = fopen("../out.txt", "wb");
- if (fout == NULL)
- return 110;
- for(int i=0;i<n;i++){
- //Sa numaram spatiile
- int nr_spatii = 0;
- for(int j = 0; j < strlen(tab[i]);j++){
- int is_whitespace = tab[i][j] == ' ' || tab[i][j] == '\n' || tab[i][j] == '\r';
- if(!is_whitespace)
- nr_spatii++;
- }
- LineInfo li;
- li.line_length = strlen(tab[i]);
- li.no_characters = nr_spatii;
- memset(li.first_chars, 0, 100);
- strncpy(li.first_chars, tab[i], 99);
- fwrite(&li, sizeof(LineInfo), 1, fout);
- // fprintf(fout,"Number of non-spaces: %-6d : %s", nr_spatii, tab[i]); <-- Here I am outputing variable length text.
- }
- fclose(fout);
- //!!!!!!!!!!!!!!!!!
- // I have n lines. So in the file I will have n structures.
- FILE * fin = fopen("../out.txt", "rb");
- if (fin == NULL)
- return 110;
- LineInfo *linfo = (LineInfo*)malloc(sizeof(LineInfo) * n);
- fread(linfo, sizeof(LineInfo), n, fin);
- for(int i=0; i<n;i++){
- printf("Read from file: %d : %d %s\n", linfo[i].no_characters, linfo[i].line_length, linfo[i].first_chars);
- }
- for(int i=0;i<n;i++){
- free(tab[i]);
- }
- free(tab);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement