Reading in data from a file into an array - c

If I have an options file along the lines of this:
size = 4
data = 1100010100110010
And I have a 2d size * size array that I want to populate the values in data into, what's the best way of doing it?
To clarify, for the example I have I'd want an array like this:
int[4][4] array = {{1,1,0,0}, {0,1,0,1}, {0,0,1,1}, {0,0,1,0}}. (Not real code but you get the idea).
Size can be really be any number though.
I'm thinking I'd have to read in the size, maloc an array and then maybe read in a string full of data then loop through each char in the data, cast it to an int and stick it in the appropriate index? But I really have no idea how to go about it, have been searching for a while with no luck.
Any help would be cool! :)

int process_file(int **array, char const *file_name)
{
int size = 0;
FILE *file = fopen(file_name, "rt");
if(fp == null)
return -1;//can't open file
char line[1024]; //1024 just for example
if(fgets(line, 1024, file) != 0)
{
if(strncmp(line, "size = ", 7) != 0)
{
fcloes(file);
return -2; //incorrect format
}
size = atoi(line + 7);
array = new int * [size];
for(int i = 0; i < size; ++i)
array[i] = new int [size];
}
else
{
fclose(file);
return -2;//incorrect format
}
if(fgets(line, 1024, file) != 0)
{
if(strncmp(line, "data = ", 7) != 0)
{
fcloes(file);
for(int i = 0; i < size; ++i)
delete [] array[i];
delete [] array;
return -2; //incorrect format
}
for(int i = 7; line[i] != '\n' || line[i] != '\0'; ++i)
array[(i - 7) / size][(i - 7) % size] = line[i] - '0';
}
else
{
fclose(file);
for(int i = 0; i < size; ++i)
delete [] array[i];
delete [] array;
return -2; //incorrect format
}
return 0;
}
Don't forget delete array before program ends;

Loops.
FILE *fp = fopen("waaa.txt", "r");
if(fp == null) { /* bleh */ return; }
int j = 0;
while(char ch = fgetc(fp)) {
for(int i = 0; i < 4; ++i) {
array[j][i] = ch;
}
++j;
}
I am not sure with the fgetc() syntax.. Just check on it. It reads one character at a time.

Related

To mimic sort command of linux, to sort lines of a text file

Sort command of linux must sort the lines of a text file and transfer the output to another file. But my code gives a runtime error. Please rectify the pointer mistakes so that output.
In which line exactly should I make changes? Because there is no output after all.
I'm pasting the whole code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sortfile(char **arr, int linecount) {
int i, j;
char t[500];
for (i = 1; i < linecount; i++) {
for (j = 1; j < linecount; j++) {
if (strcmp(arr[j - 1], arr[j]) > 0) {
strcpy(t, arr[j - 1]);
strcpy(arr[j - 1], arr[j]);
strcpy(arr[j], t);
}
}
}
}
int main() {
FILE *fileIN, *fileOUT;
fileIN = fopen("test1.txt", "r");
unsigned long int linecount = 0;
int c;
if (fileIN == NULL) {
fclose(fileIN);
return 0;
}
while ((c = fgetc(fileIN)) != EOF) {
if (c == '\n')
linecount++;
}
printf("line count=%d", linecount);
char *arr[linecount];
char singleline[500];
int i = 0;
while (fgets(singleline, 500, fileIN) != NULL) {
arr[i] = (char*)malloc(500);
strcpy(arr[i], singleline);
i++;
}
sortfile(arr, linecount);
for (i = 0; i < linecount; i++) {
printf("%s\n", arr[i]);
}
fileOUT = fopen("out.txt", "w");
if (!fileOUT) {
exit(-1);
}
for (i = 0; i < linecount; i++) {
fprintf(fileOUT, "%s", arr[i]);
}
fclose(fileIN);
fclose(fileOUT);
}
The problem in your code is you do not rewind the input stream after reading it the first time to count the number of newlines. You should add rewind(fileIN); before the next loop.
Note however that there are other problems in this code:
the number of newline characters may be less than the number of successful calls to fgets(): lines longer than 499 bytes will be silently broken in multiple chunks, causing more items to be read by fgets() than newlines. Also the last line might not end with a newline. Just count the number of successful calls to fgets().
You allocate 500 bytes for each line, which is potentially very wasteful. Use strdup() to allocate only the necessary size.
Swapping the lines in the sort routine should be done by swapping the pointers, not copying the contents.
allocating arr with malloc is safer and more portable than defining it as a variable sized array with char *arr[linecount];
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sortfile(char **arr, int linecount) {
for (;;) {
int swapped = 0;
for (int j = 1; j < linecount; j++) {
if (strcmp(arr[j - 1], arr[j]) > 0) {
char *t = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = t;
swapped = 1;
}
}
if (swapped == 0)
break;
}
}
int main() {
FILE *fileIN, *fileOUT;
char singleline[500];
int i, linecount;
fileIN = fopen("test1.txt", "r");
if (fileIN == NULL) {
fprintf(stderr, "cannot open %s\n", "test1.txt");
return 1;
}
linecount = 0;
while (fgets(singleline, 500, fileIN)) {
linecount++;
}
printf("line count=%d\n", linecount);
char **arr = malloc(sizeof(*arr) * linecount);
if (arr == NULL) {
fprintf(stderr, "memory allocation failure\n");
return 1;
}
rewind(fileIN);
for (i = 0; i < linecount && fgets(singleline, 500, fileIN) != NULL; i++) {
arr[i] = strdup(singleline);
if (arr[i] == NULL) {
fprintf(stderr, "memory allocation failure\n");
return 1;
}
}
fclose(fileIN);
if (i != linecount) {
fprintf(stderr, "line count mismatch: i=%d, lilnecount=%d\n",
i, linecount);
linecount = i;
}
sortfile(arr, linecount);
for (i = 0; i < linecount; i++) {
printf("%s", arr[i]);
}
fileOUT = fopen("out.txt", "w");
if (!fileOUT) {
fprintf(stderr, "cannot open %s\n", "out.txt");
return 1;
}
for (i = 0; i < linecount; i++) {
fprintf(fileOUT, "%s", arr[i]);
}
fclose(fileOUT);
for (i = 0; i < linecount; i++) {
free(arr[i]);
}
free(arr);
return 0;
}
To get a different sort order, you would change the comparison function. Instead of strcmp() you could use this:
#include <ctype.h>
int my_strcmp(const char *s1, const char *s2) {
/* compare strings lexicographically but swap lower and uppercase letters */
unsigned char c, d;
while ((c = *s1++) == (d = *s2++)) {
if (c == '\0')
return 0; /* string are equal */
}
/* transpose case of c */
if (islower(c)) {
c = toupper(c);
} else {
c = tolower(c);
}
/* transpose case of d */
if (islower(d)) {
d = toupper(d);
} else {
d = tolower(d);
}
/* on ASCII systems, we should still have c != d */
/* return comparison result */
if (c <= d)
return -1;
} else {
return 1;
}
}

Get length of char array with null elements in C

Currently I am making a project that uses char arrays that have null elements. I want to be able to get the length of the array, in the sense of the number of elements that aren't null. This seemed reasonably trivial and I made this function:
int getWordLen(char word[]) {
int count = 0;
for (int i = 0; i < 512; i++) {
if (word[i] != '\0') {
count++;
}
}
printf("%d ", count);
return count;
}
However, every char array returns a length of 188. Any help would be appreciated.
This is the function I was calling it from:
void redact(Words * redactWords, char fileName[]) {
FILE * file = fopen(fileName, "r");
FILE * outputFile = fopen("outputFile.txt", "w+");
char word[512];
int i = 0;
char c;
while (c != EOF) {
c = getc(file);
if ((c > 96) && (c < 123)) {
word[i] = c;
i++;
continue;
}
else if ((c > 64) && (c < 91)) {
word[i] = c + 32;
i++;
continue;
}
i = 0;
if (isWordRedactWord(redactWords, word)) {
//write stars to file
char starStr[512];
for (int i = 0; i < getWordLen(word); i++) {
starStr[i] = '*';
}
fputs(starStr, outputFile);
}
else {
//write word to file
fputs(word, outputFile);
}
strcpy(word, emptyWord(word));
}
fclose(file);
fclose(outputFile);
}
In the initial while, I would only use while(!EOF).
Also, I believe you are using a lot more resources than necessary with the implementation of that for inside the while:
char starStr[512];
for (int i = 0; i < getWordLen(word); i++) {
starStr[i] = '*';
I suggest you to put it outside the while loop and see what happens.
If it is always giving you 188 of lenght, it is counting something that's constant, and may be related to that outer loop.
Hope you can solve it!

How To Count The Number of Words Stored in A Double Pointer

I want to count the number of words that are in a file. I store each line of the text in the file using a double pointer and then manipulate it do other things.
char **create2DArray()
{
int i = 0;
char **str = malloc(sizeof(char *) * 100);
for (i = 0; i < 100; i++)
{
str[i] = malloc(sizeof(char) * 1000);
}
return str;
}
char **readFile(char **str)
{
int i = 0;
FILE *pFile;
char *filename = "C:\\Users\\muham\\OneDrive\\Documents\\A2\\A2 Samples\\sample1.txt";
pFile = fopen(filename, "r");
if (pFile == NULL)
{
printf("Could not open file");
exit(1);
}
while (fgets(str[i], 1000, pFile) != NULL)
{
RemoveReturn(str[i]);
lineCount++;
printf("%s\n", str[i]);
i++;
}
fclose(pFile);
return str;
}
int wordCount(char **str)
{
int wordCounting = 0;
int i = 0;
int q = 0;
for (i = 0; i < lineCount; i++)
{
for (q = 0; q <= strlen(str[i]); q++)
{
if (*str[q] == ' ' || *str[q] == '\0')
{
wordCounting++;
}
if (*str[q] == ' ' && *str[q + 1] == ' ' && *str[0] != ' ')
{
wordCounting--;
}
if (*str[0] == ' ')
{
wordCounting--;
}
if (*str[q] == ' ' && *str[q + 1] == '\0')
{
wordCounting--;
}
if (strlen(str[q]) == 0)
{
wordCounting--;
}
}
}
printf("%d\n", wordCounting);
return wordCounting;
}
As of right now, when I run the program, wordCount prints 0. Why is this happening? Is it because I am iterating through the number of pointers with str[i] and not the strings stored in str[i]? How do I fix this?
There are several issues in your code; The most obvious one is probably your loop for (i = 0; i <= strlen(str[i]); i++), in which you compare the length of the ith string with the value of i, and you use the same i then to access the characters of the ith string. This all rarely makes sense.
I'd start with two things:
First, make sure that you do not access uninitialized rows, i.e. consider lineCount. A simple way would be to make it either a global variable or to return it in readFile; signature would change to int readFile(char **str) { ....; return lineCount; }
Second, use two nested loops:
for (int line=0; line<lineCount; line++) {
for (int column=0; column < strlen(str[line]); column++) {
// your code for detecting lines goes here...
}
}

Alphabetical order error in C code

I have created a program that reads a series of strings from a .txt file and after compiling a new .txt file is created where the strings should be in alphabetical order.The problem is that I can't write more than 10 words, the compiler just stops/crashes, WHY? Does it depend by the type of compiler? I am currently using Code-Bloks.How can I optimize the code to run more smoothly?
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void arrange(int n, char *x[])
{
char *temp;
int i,str;
for(str = 0; str < n-1; ++str)
{
for(i = str+1; i < n; ++i)
{
if(strcmp(x[str],x[i]) > 0)
{
temp = x[str];
x[str] = x[i];
x[i] = temp;
}
}
}
return;
}
int number_of_lines = 0;
void countOfLinesFromFile(char *filename){
FILE* myfile = fopen(filename, "r");
int ch;
do
{
ch = fgetc(myfile);
if(ch == '\n')
number_of_lines++;
}
while (ch != EOF);
if(ch != '\n' && number_of_lines != 0)
number_of_lines++;
fclose(myfile);
return number_of_lines;
}
int main()
{
int i , ts=0;
char *x[10];
char *fileName = "WORDS.txt";
countOfLinesFromFile(fileName);
printf("%d",number_of_lines);
FILE * fp;
fp = fopen ("WORDS.txt", "r");
for(i = 0; i < number_of_lines; i++)
{
x[i] = (char*) malloc (1200*sizeof(char));
fscanf(fp, "%s", x[i]);
}
FILE *fPointer;
fPointer=fopen("Alphabetical.txt","w+");
arrange(i,x);
for(i = 0; i < number_of_lines; i++)
{
fprintf(fPointer,"%s\n",x[i]);
}
fclose(fPointer);
fclose(fp);
return 0;
}
char *x[10];
The buffer size is too small
These two lines define how much information you can store
char *x[10]; // 10 strings
x[i] = (char*) malloc (1200*sizeof(char)); // 1200 characters each
As it is written now, you can only hold a maximum of 10 strings with each string being no longer than 1200 characters.
The crash is caused when number_of_lines >= 11 in the following for loop:
for(i = 0; i < number_of_lines; i++)
{
x[i] = (char*) malloc (1200*sizeof(char));
fscanf(fp, "%s", x[i]);
}
When i is 11 you write to x[11] which is past the end of x.

Reading from csv file and dynamic memory allocation

My code has a memory leak problem. I don't know where I went wrong. Below is the code: I am trying to read from csv file and store a particular columns.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
FILE *result = fopen ("C:\\Users\\pa1rs\\Desktop\\local.csv", "w");
const char *text = "LOA,NAME,";
fprintf (result, "%s", text);
char *token;
char *endToken;
int lines = 0;
char ch; /* should check the result */
FILE *file = fopen ("C:\\Users\\pa1rs\\Desktop\\samplee.csv", "r");
char line[300];
if (file == NULL) {
perror ("Error opening the file");
} else {
while (!feof (file)) {
ch = fgetc (file);
if (ch == '\n') {
lines = lines + 1;
}
}
//printf(" no of lines existing in the file %d\n\n", lines);
}
fseek (file, 0, SEEK_SET);
while ((ch = fgetc (file)) != '\n') {
// we don't need the first line on sample.csv
// as it is just the description part
}
int s[lines - 1];
int j = 0;
char *N[lines - 1];
while (fgets (line, sizeof (line), file)) {
int i = 0;
token = line;
do {
endToken = strchr (token, ',');
if (endToken)
*endToken = '\0';
if (i == 3) {
s[j] = atoi (token);
}
if (i == 12) {
N[j] = (char *) malloc (strlen (token) * sizeof (char));
strcpy (N[j], token);
}
if (endToken)
token = endToken + 1;
i++;
} while (endToken);
j = j + 1;
}
//******************************************************unigue loa
int count = 0;
int g = 0;
int h = 0;
int LOA[lines - 1];
int dd = 0;
for (dd = 0; dd < lines - 1; dd++) {
LOA[dd] = 0;
}
for (g = 0; g < lines - 1; g++) {
for (h = 0; h < count; h++) {
if (s[g] == LOA[h])
break;
}
if (h == count) {
LOA[count] = s[g];
count++;
}
}
int xw = 0;
for (xw = 0; xw < count; xw++) {
//printf("%d \t",LOA[xw]);
}
//printf("LOA Array Length is: %d \n",count);
//********************************************************
////FOR UNIQUE NAMES ARRAY
//printf("No of unique names are %d",county);
//FOR UNIQUE CAUSES ARRAY
char *sa[9] =
{ "Monticello", "Valparaiso", "Crown Point", "Plymouth", "Goshen",
"Gary", "Hammond", "Laporte", "Angola" };
int countz = 0;
int gz = 0;
int hz = 0;
char *LOAz[lines - 1];
int zero2 = 0;
for (zero2 = 0; zero2 < lines - 1; zero2++) {
LOAz[zero2] = NULL;
}
for (gz = 0; gz < lines - 1; gz++) {
for (hz = 0; hz < countz; hz++) {
if (strcmp (N[gz], LOAz[hz]) == 0)
break;
}
if (hz == countz) {
LOAz[countz] = (char *) malloc (strlen (N[gz]) * sizeof (char));
strcpy (LOAz[countz], N[gz]);
countz++;
}
}
int nz = 0;
for (nz = 0; nz < countz; nz++) {
fprintf (result, "%s,", LOAz[nz]);
}
fprintf (result, "\n");
// printf("%d",countz);
//*****************************
int i = 0;
int jjj = 0;
int xxx = 0;
int ggg = 0;
int k = 0;
int kount[count][countz];
for (xxx = 0; xxx < count; xxx++) {
for (ggg = 0; ggg < countz; ggg++) {
kount[xxx][ggg] = 0;
}
}
for (i = 0; i < count; i++) {
for (k = 0; k < countz; k++) {
for (jjj = 0; jjj < lines - 1; jjj++) {
if (LOA[i] == s[jjj]) {
if (strcmp (LOAz[k], N[jjj]) == 0) {
kount[i][k]++;
}
}
}
}
}
int ig = 0;
int ik = 0;
for (ig = 0; ig < count; ig++) {
fprintf (result, "%d,%s", LOA[ig], sa[ig]);
for (ik = 0; ik < countz; ik++) {
fprintf (result, ",%d", kount[ig][ik]);
}
fprintf (result, "\n");
}
int rrr = 0;
free (N);
for (rrr = 0; rrr < lines - 1; rrr++) {
free (LOAz[rrr]);
}
//*****************************
//fclose(result);
fclose (file);
return 0;
}
Lines I got here is 13761 and LOAz was declared with array size lines-1=13761, but unique ones I got here are only 49, So I am reallocating memory for that and remaining are unused , I think problem started there.
Please help! Thanks in Advance.
One problem in your code is that you don't allocate enough memory for strings. For example, in these lines:
N[j] = (char*) malloc(strlen(token) * sizeof(char));
strcpy(N[j], token);
// ...
LOAz[countz] = (char*) malloc(strlen(N[gz]) * sizeof(char));
strcpy(LOAz[countz], N[gz]);
The problem is that strlen returns the number of non-zero symbols in the string. However, to store the string you need one more byte, to also store the zero terminating character, so the buffer size to store s should be at least strlen(s) + 1.
Also, a better coding style is to avoid casting the return value of malloc.

Resources