Read from a file and store it in 2d array - c

I am working on a function that reads from a file (fp) and stores in the words array. I declared MAX_WORD_SIZE as 128, but when I input any file into this function and check with valgrind, it tells me I have an uninitialized value in the line "while(getline(&line,&count,fp)!=-1)" I really don't get it: what is the uninitialised value? My fp file is valid and the word array is also declared well. Thank you in advance.
#include "functions.h"
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int read_file(FILE *fp, char words[][MAX_WORD_SIZE + 1], int size) {
int i=0;int j=0;
size_t count=MAX_WORD_SIZE;
char* line=malloc(MAX_WORD_SIZE);
while(getline(&line,&count,fp)!=-1){
for(;count>0;count--,j++){
sscanf(line,"%c",&words[i][j]);
}
i++;
}
int totalNums = i;
int totalNum = j;
if (i<size){
return 1;
}
fclose(fp);
return 0;
}
This is the function that I called this read_file function:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "functions.h"
int main(int argc, char *argv[]) {
const char* fileName = argv[1];
FILE *fp = fopen(fileName, "r");
if (fp == NULL) {
printf("Invalid input file\n");
return 1;
}
int size = 0;
int validity = fscanf(fp, "%d", &size);
int returnValue = 0;
char words[size][MAX_WORD_SIZE + 1];
if(validity != 1 || size <= 0) {
printf("The first line is not a valid number\n");
return 1;
}
returnValue = read_file(fp, words, size);
if (returnValue == 1) {
fclose(fp);
return 1;
}
return 0;
}

Related

Issue writing strings to a file

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#define KEYSIZE 16
int main(){
FILE *fptr;
fptr = fopen("program.txt", "w");
if (fptr == NULL) {
printf("Error!");
exit(1);
}
int num_keys = 1524006529 - 1523999329;
const char *keys[num_keys];
int idx = 0;
int j;
for (j = 1523999329; j<= 1524006529; j++){
int i;
char key[KEYSIZE];
srand (j);
for (i = 0; i< KEYSIZE; i++){
key[i] = rand()%256;
printf("%.2x", (unsigned char)key[i]);
fprintf(fptr, "%.2x", (unsigned char)key[i]);
}
fprintf(fptr, "%s", "\n");
printf("\n");
keys[idx] = key;
idx ++;
}
fclose(fptr);
return 0;
}
I want to create a text file (program.txt) that has a new string key variable on each line. The code above produces a txt file that has this content though:
h?G??+?
Mp???+??
a?G????#*Jb`e0?H?????G??????
S6&}?Μ??G??OFf??|???s8f?G????ɼ???5q??(???K?G?? ??J????9?+???G?????cZ?n0?Jr?G?????#O9]??????jH??G???krT?̇)?A
?g?v?G??????h^(?^?
û/?G???^vB?~W?39???G??\????"?iJ_????G??p??>??????I???U?G????????:??o?RV???G??/?C?^?????|?۬?G??q#0.L$+??Nv?????G????u? L?Ϩ????dv?G??[??C「<??i???G??UyM??Ƭ/??CxXUě?G?????φ
׏:W&?G????=J???o???I??G???G%DA+"?~5?Z¡?G??øL#??O=e?b?u.O?G????*jjɥ+T?)?օ?G??2w }a,ȃ??tC?s?G??J"/c??Mn???f?y??G????p?Ay?c????~"<?G?????Ӆ?=%??#???G??o?\??<w???4WϚBE?G??}oh??(??#HK???&?G????Vfz
???e?s?G??/?Ye??iV?؛?,-te?G??I?Ҁx??5?B!b?4?G??6Z??9?P?GcB?}???Y?~|"??dd??G??????=?ms?
??G?????^??[H??\:???G??2(J??A??????G???????o#?i?/???G??P?5?5?5X??
What am I doing wrong here?

Selecting random line from array c

So far I have read all my data into an array
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdlib.h>
int main(void) {
int i=0;
char* string[100];
char line[100];
FILE *file;
file = fopen("plates.txt", "r");
while(fgets(line, sizeof line, file)!=NULL) {
printf("%s",line);
string[i]=line;
i++;
}
fclose(file);
return 0;
}
but i want to now select a random line of my array and print it. All lines need to have an equal chance of being selected but they can only be selected once. Im not too sure how to do this...
Thank you in advance
Please be mindful of this line string[i]=line as it makes all the array entries in string that you set all point to the last line read which is not what you want and it's pretty important to understand that.
That said, here's a solution to the problem that assumes we can just store all the lines in memory and on the stack:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAX_LINE_LENGTH 128
#define MAX_LINE_COUNT 1000
int main(int argc, char **argv) {
char lines[MAX_LINE_COUNT][MAX_LINE_LENGTH];
int numLines = 0;
if (argc < 2) {
fprintf(stderr, "missing file name\n");
return EXIT_FAILURE;
}
FILE *fp = fopen(argv[1], "r");
if (fp != NULL) {
while (fgets(lines[numLines++], MAX_LINE_LENGTH, fp)) {
printf("%03d> %s", numLines, lines[numLines-1]);
}
fclose(fp);
srand (time(NULL));
int randomIndex = rand() % numLines;
printf("Selected random line #%d> %s", randomIndex+1, lines[randomIndex]);
} else {
fprintf(stderr, "file '%s' not found\n", argv[1]);
return EXIT_FAILURE;
}
}
And the corresponding output:
➜ ~ gcc random-line.c && ./a.out random-line.c
001> #include <stdio.h>
002> #include <stdlib.h>
003> #include <string.h>
004> #include <time.h>
005>
006> #define MAX_LINE_LENGTH 128
007> #define MAX_LINE_COUNT 1000
008>
009> int main(int argc, char **argv) {
010> char lines[MAX_LINE_COUNT][MAX_LINE_LENGTH];
011> int numLines = 0;
012>
013> if (argc < 2) {
014> fprintf(stderr, "missing file name\n");
015> return EXIT_FAILURE;
016> }
017>
018> FILE *fp = fopen(argv[1], "r");
019> if (fp != NULL) {
020> while (fgets(lines[numLines++], MAX_LINE_LENGTH, fp)) {
021> printf("%03d> %s", numLines, lines[numLines-1]);
022> }
023> fclose(fp);
024> srand (time(NULL));
025> int randomIndex = rand() % numLines;
026> printf("Selected random line #%d> %s", randomIndex+1, lines[randomIndex]);
027> } else {
028> fprintf(stderr, "file '%s' not found\n", argv[1]);
029> return EXIT_FAILURE;
030> }
031> }
Selected random line #2> #include <stdlib.h>

Warning When Returning Pointer

My file include 1 word in every line(i know the number of the line).I want to read random line, store it's adress in pointer and return to main function. There is 1 warning (19|warning: return makes pointer from integer without a cast [-Wint-conversion]|) and when i run the program it dont prints anything.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
char *word(char *file, char *str);
int main() {
char *str;
printf("%s",word("words.txt",str));
}
char *word(char *file, char *str) {
int end, loop, line;
FILE *fd = fopen(file, "r");
if (fd == NULL) {
printf("Failed to open file\n");
return -1;
}
srand(time(NULL));
line = rand() % 100 + 1;
for (end = loop = 0; loop < line; ++loop) {
if (0 == fgets(str, sizeof(str), fd)) {
end = 1;
break;
}
}
if (!end)
return (char*)str;
fclose(fd);
}

Converting Greek words to uppercase

I have to create a function that reads a file called grwords.txt containing around 540000 words which are written in Greek letters.
I have to convert these words to uppercase and fill an array called char **words.
This is what I have so far.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <windows.h>
#include <ctype.h>
void fp();
int main(int argc, char *argv[]) {
SetConsoleOutputCP(1253);
fp();
return 0;
}
void fp(){
char **words;
words = malloc(546490 * sizeof(int *));
for (i = 0; i < 546490; i++)
words[i] = malloc(24 * sizeof(int));
FILE *file;
char *word;
size_t cnt;
file = fopen("grwords.txt", "rt");
if (file == NULL){
printf("File cannot be opened.\n");
exit(1);
}
cnt = 0;
while (1==fscanf(file, "%24s",word)){
if (cnt == 546490)
break;
strcpy(words[cnt++], word);
}
fclose(file);
}
I'm still trying to figure out pointers. I know that & makes a pointer from a value and * a value from a pointer. Updated the program and it successfully fills the array with the words from the file! I still have no idea how to convert Greek lowercase to uppercase.
Handling Greek words can be dependent on your platform.
First of all, you need to understand how file handling works. Here is what I wrote:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define bufSize 1024 // max lenght of word
// we are going to receive the .txt from cmd line
int main(int argc, char *argv[])
{
FILE *fp;
// Assume file has max 10 words
const size_t N = 10;
// Allocate a 2D array of N rows
// and bufSize columns.
// You can think of it like an array
// of N strings, where every string
// has, at most, bufSize length.
char buf[N][bufSize];
// make sure we got the .txt
if (argc != 2)
{
fprintf(stderr,
"Usage: %s <soure-file>\n", argv[0]);
return 1;
}
// open the file
if ((fp = fopen(argv[1], "r")) == NULL)
{ /* Open source file. */
perror("fopen source-file");
return 1;
}
// we will use that for toupper()
char c;
// counters
int i = 0, j;
while (fscanf(fp, "%1024s", buf[i]) == 1)
{ /* While we don't reach the end of source. */
/* Read characters from source file to fill buffer. */
// print what we read
printf("%s\n", buf[i]);
j = 0;
// while we are on a letter of word placed
// in buf[i]
while (buf[i][j])
{
// make the letter capital and print it
c = buf[i][j];
putchar (toupper(c));
j++;
}
i++;
printf("\ndone with this word\n");
}
// close the file
fclose(fp);
return 0;
}
For this test.txt file:
Georgios
Samaras
Γιώργος
Σαμαράς
the code would run as:
./exe test.txt
Georgios
GEORGIOS
done with this word
Samaras
SAMARAS
done with this word
Γιώργος
Γιώργος
done with this word
Σαμαράς
Σαμαράς
done with this word
As you can see, I could read the Greek words, but failed to convert them in upper case ones.
Once you got how file handling goes, you need to use wide characters to read a file with Greek words.
So, by just modifying the above code, we get:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <wchar.h>
#include <wctype.h>
#include <locale.h>
#define bufSize 1024
int main(int argc, char *argv[])
{
setlocale(LC_CTYPE, "en_GB.UTF-8");
FILE *fp;
const size_t N = 15;
wchar_t buf[N][bufSize];
if (argc != 2)
{
fprintf(stderr,
"Usage: %s <soure-file>\n", argv[0]);
return 1;
}
if ((fp = fopen(argv[1], "r")) == NULL)
{
perror("fopen source-file");
return 1;
}
wchar_t c;
int i = 0, j;
while (fwscanf(fp, L"%ls", buf[i]) == 1)
{
wprintf( L"%ls\n\n", buf[i]);
j = 0;
while (buf[i][j])
{
c = buf[i][j];
putwchar (towupper(c));
j++;
}
i++;
wprintf(L"\ndone with this word\n");
}
fclose(fp);
return 0;
}
And now the output is this:
Georgios
GEORGIOS
done with this word
Samaras
SAMARAS
done with this word
Γιώργος
ΓΙΏΡΓΟΣ
done with this word
Σαμαράς
ΣΑΜΑΡΆΣ
done with this word
I see that you may want to create a function which reads the words. If you need a simple example of functions in C, you can visit my pseudo-site here.
As for the 2D array I mentioned above, this picture might help:
where N is the number of rows (equal to 4) and M is the number of columns (equal to 5). In the code above, N is N and M is bufSize. I explain more here, were you can also found code for dynamic allocation of a 2D array.
I know see that you are on Windows. I tested the code in Ubuntu.
For Windows you might want to take a good look at this question.
So, after you read all the above and understand them, you can see what you asked for with dynamic memory management.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <wchar.h>
#include <wctype.h>
#include <locale.h>
#define bufSize 1024
wchar_t **get(int N, int M);
void free2Darray(wchar_t** p, int N);
int main(int argc, char *argv[])
{
setlocale(LC_CTYPE, "en_GB.UTF-8");
FILE *fp;
const size_t N = 15;
wchar_t** buf = get(N, bufSize);
if (argc != 2)
{
fprintf(stderr,
"Usage: %s <soure-file>\n", argv[0]);
return 1;
}
if ((fp = fopen(argv[1], "r")) == NULL)
{
perror("fopen source-file");
return 1;
}
wchar_t c;
int i = 0, j;
while (fwscanf(fp, L"%ls", buf[i]) == 1)
{
wprintf( L"%ls\n", buf[i]);
j = 0;
while (buf[i][j])
{
c = buf[i][j];
putwchar (towupper(c));
j++;
}
i++;
wprintf(L"\ndone with this word\n");
}
fclose(fp);
// NEVER FORGET, FREE THE DYNAMIC MEMORY
free2Darray(buf, N);
return 0;
}
// We return the pointer
wchar_t **get(int N, int M) /* Allocate the array */
{
/* Check if allocation succeeded. (check for NULL pointer) */
int i;
wchar_t **table;
table = malloc(N*sizeof(wchar_t *));
for(i = 0 ; i < N ; i++)
table[i] = malloc( M*sizeof(wchar_t) );
return table;
}
void free2Darray(wchar_t** p, int N)
{
int i;
for(i = 0 ; i < N ; i++)
free(p[i]);
free(p);
}
Note that this code is expected to work on Linux (tested on Ubuntu 12.04), not on Windows (tested on Win 7).

Reading Text In C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 500
int main(){
int JourneyId;
char Date[MAX];
int Hour;
char BusDriver[MAX];
char Departure[MAX];
char Destination[MAX];
int BusCapacity;
FILE * file;
file = fopen( "Journey.txt" , "rt");
if(file){
while (fscanf(file,"%d,%s,%d,%20[^,],%20[^,],%20[^,],%d", &JourneyId,Date,&Hour,BusDriver,Departure,Destination, &BusCapacity) != EOF){
printf("%d,",JourneyId);
printf("%s",BusDriver);
}
}
else{
printf("Error");
}
return 1;
}
I want to read text file and use this code for adding BST.But If I run , Output is infinite loop.How can I read text file ?
Text file which I want to read:
80,15.04.2014,10,Henry Ford,NewYork,Paris,45
40,15.04.2014,11,Nikola Tesla,Londra,NewYork,40
Rather than read a text file using fscanf(), strongly recommend using fgets() and then parsing via sscanf(), strtok(), strtol(), etc. Check all function return values. It is much easier to cope with the unexpected - which is certainly what is happening in OP's case.
Using modified format from #BLUEPIXY
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 500
int main() {
int JourneyId;
char Date[MAX];
int Hour;
char BusDriver[MAX];
char Departure[MAX];
char Destination[MAX];
int BusCapacity;
FILE * file;
file = fopen("Journey.txt", "rt");
if (file) {
char buf[MAX*4 + 20*3 + 6*1 + 3];
while (fgets(buf, sizeof buf, stdin) != NULL) {
int cnt = sscanf(buf, "%d,%499[^,],%d,%499[^,],%499[^,],%499[^,],%d",
&JourneyId, Date, &Hour, BusDriver, Departure, Destination,
&BusCapacity);
if (cnt != 7) {
printf("Unexpected input \"%s\"", buf);
break;
}
printf("%d,", JourneyId);
printf("%s\n", BusDriver);
}
fclose(file); // Be sure to close
} else {
printf("Error opening\n");
}
return 1;
}
As #BLUPIXY indicated, The following functions (tried on SuSE Linux / gcc)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 500
int main(){
int JourneyId;
char Date[MAX];
int Hour;
char BusDriver[MAX];
char Departure[MAX];
char Destination[MAX];
int BusCapacity;
FILE *file;
file = fopen( "Journey.txt" , "rt");
if(file)
{
// while(fscanf(file,"%d,%s,%d,%20[^,],%20[^,],%20[^,],%d", &JourneyId,Date,&Hour,BusDriver,Departure,Destination, &BusCapacity) != EOF){
while(fscanf(file,"%d,%11[^,],%d,%20[^,],%20[^,],%20[^,],%d", &JourneyId,Date,&Hour,BusDriver,Departure,Destination, &BusCapacity) != EOF){
printf("%d,",JourneyId);
printf("%s",BusDriver);
}
}
else
{
printf("Error");
}
return 1;
}

Resources