I have a text file with 25 lines, each with 34 characters on.
In C how is it possible to load these characters and store them into a 2D array?
If the first three lines of the file are such:
bamaaaaaaaacxxxxxxxxxxbaaaaaaaamac
jzjzzzzzzzzdaaaaaaaaaaezzzzzzzzjzj
jzjzbaaczgzzzzzzzzzzzzzzgzbaaczjzj
...and so on
I require the array to be stored as if it was defined like this:
char* data[] = {
"baaaaaaaaaaaaaacxxbaaaaaaaaaaaaaac",
"jzzzzzzzzzzzzzzjxxjzzzzzzzzzzzzzzj",
"jzbaaaaaaaaaaaaexxdaaaaaaaaaaaaczj",
...and so on
Hopefully this makes some sense! It is important that the type of data is char data[][] as it is used in that format in the rest of my project and cannot be changed.
I have done the basic begining of the File IO
FILE *infp;
printf("Opening file\n");
if((infp = fopen("file.txt", "r"))== NULL) {
printf("\nERROR : Unable to open input file\n");
SetExitWithCode( 999 );
}else{
//code here
}
Can anyone help?
So, you want your array to look like this:
char data[25][35] //There is an extra 1 character per line to hold the null terminator character
Then simply read the whole file into that array
fread(data, 1, sizeof(data), infp);
And finally, replace the new line character in on each line with a terminator
for (int i = 0; i < 25; ++i) {
data[i][34] = 0;
}
This is the easiest solution to the problem, but it is also a bad way of doing it. It does not validate that the data is in the correct format, and everything is hard coded.
Related
I am kind of new when it comes to C. Took a class on it in college but I just don't practice it much. Well my issue that I'm having is that I'm trying to take an text file and convert it into an array. I have been able to get the text file and print it into the console but when I save run the while statement to read each line, my whole array gets overwritten. For instance if my last line on my text file is 19, my array[0] gets over written to what should be on array[18].
I know the indentations are off a off, coding is a mess, and forgive me on the printf commands, I'm only using them to troubleshoot my code. The text file will have IP address on each line.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#define MAX_LINE_LENGTH 16
int main()
{
int lineCntPOSlist = 0;
int lineCnt = 0;
int i = 0;
FILE *textfile;
char line[MAX_LINE_LENGTH];
char* posList[50];
textfile = fopen("pos-list.txt", "r");
if(textfile == NULL)
{
int posListExist = 0;
system("cls");
printf("File Exist %d\n", posListExist);
fprintf(stderr, "**File open failed\n Make sure there is a pos-list.txt file");
return 1;
}
system("cls");
while(fgets(line, MAX_LINE_LENGTH, textfile))
{
printf("Line %d: %s",lineCnt , line);
posList[lineCnt] = line;
printf("posList[%d] = %s\n", lineCnt, posList[lineCnt] );
printf("posList[0] = %s\n", posList[0] );
lineCnt = ++lineCnt;
lineCntPOSlist = ++lineCntPOSlist;
}
fclose(textfile);
return 0;
}
This:
posList[lineCnt] = line;
simply sets posList[lineCnt] to point at the line buffer in line, it copies zero characters of actual data. In higher-level languages where strings have a bit more presence, this would make sense, but in C it doesn't.
Since there is only one line buffer, it will always hold the characters making up the most recently loaded line, and thus it will act as if previous lines are being "overwritten".
There are several solutions, here are a few:
Make posList into a proper array of strings, but that requires you to decide max length in advance and will waste the space for shorter lines.
Use something like strdup() to allocate copies on the heap of each line, and store pointers to those.
Use a more "proper" reallocating array for the storage and store line pointers (or offsets, which might be better suited due to the reallocating) in the array for easier access.
Newbie here. I need to create a program that reads strings from a textfile.txt then processes a few characters from it.
The contents of textfile.txt is as below.
JA100200300
FE111222333
MA101202303
I need to reference "JA","100", "200" and "300" separately. I managed to do this with the code below, where I split the string into 11 characters and put it into array. Of course this code works only as you type out the string. I need a way to do the same thing but get the string from a file instead.
while((a[i++]=getchar()) != '\n' && i < 11);
How do I do this? Can I read the file and put each line of string into an array, then read from the array and split each array into multiple arrays? Is that possible? Or read each character from the file and put them into arrays something like fscanf %d but split each character?
You might want something like this:
FILE fp = fopen("data.txt","r");
char line[100] = { 0 }, str1[3], str2[4], str3[4], str4[4];
if (!fp) {
perror("opening file");
exit(1);
}
while(fgets(line,sizeof line,fp)) {
strncpy(str1,line,2);
str1[2] = '\0';
strncpy(str2,&line[2],3);
str2[3] = '\0';
strncpy(str3,&line[5],3);
str3[3] = '\0';
strncpy(str4,&line[8],3);
str4[3] = '\0';
}
I'm getting some issues with reading the content of my array. I'm not sure if I'm storing it correctly as my result for every line is '1304056712'.
#include <stdio.h>
#include <stdlib.h>
#define INPUT "Input1.dat"
int main(int argc, char **argv) {
int data_index, char_index;
int file_data[1000];
FILE *file;
int line[5];
file = fopen(INPUT, "r");
if(file) {
data_index = 0;
while(fgets(line, sizeof line, file) != NULL) {
//printf("%s", line); ////// the line seems to be ok here
file_data[data_index++] = line;
}
fclose(file);
}
int j;
for(j = 0; j < data_index; j++) {
printf("%i\n", file_data[j]); // when i display data here, i get '1304056712'
}
return 0;
}
I think you need to say something like
file_data[data_index++] = atoi(line);
From your results I assume the file is a plain-text file.
You cannot simply read the line from file (a string, an array of characters) into an array of integers, this will not work. When using pointers (as you do by passing line to fgets()) to write data, there will be no conversion done. Instead, you should read the line into an array of chars and then convert it to integers using either sscanf(), atoi() or some other function of your choice.
fgets reads newline terminated strings. If you're reading binary data, you need fread. If you're reading text, you should declare line as an array of char big enough for the longest line in the file.
Because file_data is an array of char, file_data[data_index] is a single character. It is being assigned a pointer (the base address of int line[5] buffer). If reading binary data, file_data should be an array of integers. If reading strings, it should be an array of string, ie char pointers, like char * file_data[1000]
you also need to initialize data_index=0 outside the if (file) ... block, because the output loop needs it to be set even if the file failed to open. And when looping and storing input, the loop should test that it's not reached the size of the array being stored into.
I'm working on learning C and decided to port my Game of Life code over from Java. It doesn't seem too difficult except that the FileIO part. My input file looks something like:
Beehive
5 6
------
--XX--
-X--X-
--XX--
------
Here's the pseduo-code of what I did in Java;
Scanner to open the file,
String line = file.nextLine(),
print the line,
get the second line
Trim and split the firstLine,
String[tokens[0]][tokens[1]],
while(line != NULL) -> string[row][col] = input.charAt(i);
close input,
return string[][]
This is what I have so far in C,
void fileIO() {
FILE *file;
char buffer[BUFFER_SIZE];
file = fopen("INPUT_FILE", "r");
if(file == NULL) {
printf("Cannot open file!");
}
while(fgets(buffer, BUFFER_SIZE, file) != NULL ) {
}
}
I'm not sure how to proceed from here? Can anyone give me a pointer in which way to go from here?
To print a line: puts
puts(buffer);
Note that after fgets, buffer contains the newline character \n, which will be printed too. I guess you want this behavior (not sure how this works in Java).
To trim and split a line: sscanf
int height, width;
...
sscanf(buffer, "%d%d", &height, &width);
To extract a character from a string (instead of input.charAt(i)):
char c = buffer[i];
This is not file I/O; it's just the C syntax for getting a character from a string.
It seems that you have a function in Java that returns a 2-D array (of characters? of strings?), which is dynamically allocated. Java supports recording the width and height in the array object itself, while C doesn't support this. Instead of the 2-D array, you will have to use a struct:
struct MyDataFromFile
{
int height, width;
bool **data;
};
Such data structure is only one possible option; you could use different options:
bool[MAX_HEIGHT][MAX_WIDTH] - convenient if there is maximum height and width
uint64_t *data if you want to use 1 bit for storage, instead of 1 byte - this requires additional bit-fiddling
I am trying to read a series of names from a text file and save them into an array.
Everything looked okay until I try to reference a specific name by using indexes (ex: array[0] ). It gives me t25.txt where it should of give me t1.txt. What did I do wrong?
Here's what I have:
#define MAX_STRING 25
FILE *in;
in = fopen("filenames.txt", "r");
if (!in) {
printf("Failed to open the file\n");
exit(1);
}
char array[MAX_STRING];
// In my mind, I want it to look like this:
// array[0] = t1.txt
// array[1] = t2.txt
int i;
for ( i = 0; i < MAX_STRING; i++ ) // Get 25 words
{
fscanf( in, "%s", array);
printf( "filename = %s\n", array);
// I print it out to make sure it's getting what i want and it did
}
My text file - filenames.txt is something like this
t1.txt
t2.txt
Thanks much
char array[MAX_STRING];
is an array of characters, not an array of strings. Your loop overwrites this array in every iteration. You might have meant something like
char array[N_STRINGS][MAX_LENGTH_OF_A_SINGLE_STRING];
You aren't saving multiple strings in one array, you are overwriting one string multiple times.
In C each string is saved as an array, so you have to have something like a 2D-Array: Dimension 1: the String, Dimension 2: The "array":
array[MAX_STRING][MAX_NAME_LEN]
This is what you intend to do!
You have to understand C-Strings as an Array of Characters in continous memmory, with a \0 at the end to identify the end of the "string". You are handling with arrays when you are handling with strings!
you define char array[MAX_STRING]; which simply defines one string
so
array[0] = 't'
array[1] = 'x'
What you need is char array[NUM_STRING][MAX_STRING]