Infinite Loop While Modifying Binary File - c

I am trying to open a binary file read a part from it and then modify it but this ends up in an infinite loop.
Things I had in mind before writing the program:
EOF is a value that is returned by a function that reads/writes from/to the stream when End of file is found or if an error occurs.
File indicator will go the size of the bytes it read plus to right with every successful read/write.
(i.e. if position indicator is at 0 position it will go to position 44 if it reads/writes 44 bytes after a successful read/write.)
The code below is one of my many approaches with no success:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stoixeia
{
char e[30];
char t[5];
float mo;
int ilikia;
};
int main(void)
{
FILE *fptr;
struct stoixeia st;
int c;
if((fptr = fopen("sxoleio","rb+")) == NULL)
exit(1);
while((c = fread(&st,sizeof(struct stoixeia),1,fptr)) != EOF)
{
fseek(fptr,-44,SEEK_CUR);
for(int i = 0; i < strlen(st.e); i++)
st.e[i] += 1;
fwrite(&st,sizeof(struct stoixeia),1,fptr);
}
fclose(fptr);
return 0;
Other unsuccessful approaches:(feof,check for eof inside the loop etc.)
The only success I had so far was with the code below:
while((c = fgetc(fptr)) != EOF)
{
fseek(fptr,-1,SEEK_CUR);
fread(&st,sizeof(struct stoixeia),1,fptr);
fseek(fptr,-44,SEEK_CUR);
for(int i = 0; i < strlen(st.e); i++)
st.e[i] += 1;
fwrite(&st,sizeof(struct stoixeia),1,fptr);
fseek(fptr,1,SEEK_CUR);
fseek(fptr,-1,SEEK_CUR);
}
fclose(fptr);
Using fgetc() as the while condition and moving indicator by one byte to the right after the operations and then moving it back by one byte seems to trigger EOF and the program ends with success.
What is the reason for this behavior?
I really want to understand the behavior for this so anything would be much appreciated.
Thanks in advance.

There are a few issues with your code, but I think the biggest misconception is the return value of fread. Its return value should not be compared to EOF. When you reach end of file, fread will return a short count. In this case, that means it will return zero. Try:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stoixeia {
char e[30];
char t[5];
float mo;
int ilikia;
};
static void die(const char *msg) { perror(msg); exit(EXIT_FAILURE); }
int
main(int argc, char **argv)
{
FILE *fptr;
struct stoixeia st;
size_t c;
const char *path = argc > 1 ? argv[1] : "sxoleio";
if( (fptr = fopen(path, "rb+")) == NULL ){
die(path);
}
while( (c = fread(&st, sizeof st, 1, fptr)) == 1 ){
if( fseek(fptr, -sizeof st, SEEK_CUR) == -1 ){
die("fseek");
}
for( size_t i = 0; st.e[i] && i < sizeof st.e; i++ ){
st.e[i] += 1;
}
if( fwrite(&st, sizeof st, 1, fptr) != 1 ){
die("fwrite");
};
}
if( fclose(fptr) ){
die("fclose");
}
return EXIT_SUCCESS;
}
But, it's probably cleaner to skip the seeks completely and use two different file handles. Something like:
if( (rf = fopen(path, "r")) == NULL) {
die(path);
}
if( (wf = fopen(path, "r+")) == NULL) {
die(path);
}
while( (c = fread(&st, sizeof st, 1, rf)) == 1) {
for( size_t i = 0; st.e[i] && i < sizeof st.e; i++ ){
st.e[i] += 1;
}
if( fwrite(&st, sizeof st, 1, wf) != 1 ){
die("fwrite");
};
}

Related

pallindrome is not copied to next file but printed on output screen

I have a file named fp1 containing different names, some being palindromes, and have to read all names from fp1 and check if each name is a palindrome or not. If it's a palindrome the I need to print the name to screen and copy it to another file named fp.
Here's my program:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void main() {
FILE *fp, *fp1;
char m, y[100];
int k = 0, i = 0, t = 1, p = 0;
fp = fopen("C:\\Users\\HP\\Desktop\\New folder\\file 2.txt", "w");
fp1 = fopen("C:\\Users\\HP\\Desktop\\New folder\\file4.txt", "r");
if (fp == NULL) {
printf("error ");
exit(1);
}
if (fp1 == NULL) {
printf("error");
exit(1);
}
k = 0;
m = fgetc(fp1);
while (m != EOF) {
k = 0;
i = 0;
t = 1;
p = 0;
while (m != ' ') {
y[k] = m;
k = k + 1;
m = fgetc(fp1);
}
p = k - 1;
for (i = 0; i <= k - 1; i++) {
if (y[i] != y[p]) t = 0;
p = p - 1;
}
if (t == 1) {
fputs(y, fp);
printf("%s is a pallindrome\n", y);
}
m = fgetc(fp1);
}
fclose(fp);
fclose(fp1);
}
coping pallindrome from one file to next file
You are not null terminating your buffer before attempting to use the contents as a string. After placing the last valid character read by fgetc into the buffer, you must place a null terminating character (\0).
A character buffer without a null terminating byte is not a string. Passing such a buffer to fputs, or the printf specifier %s without a length bound, will invoke Undefined Behaviour.
fgetc returns an int, not a char. On systems where char is unsigned, you will not be able to reliably test against the negative value of EOF.
The inner while loop is not checking for EOF. When the file is exhausted, it will repeatedly assign EOF to the buffer, until the buffer overflows.
To that end, in general, the inner while loop does nothing to prevent a buffer overflow for longer inputs.
In a hosted environment, void main() is never the correct signature for main. Use int main(void) or int main(int argc, char **argv).
Note that fputs does not print a trailing newline. As is, you would fill the output file full of strings with no delineation.
The nested while loops are fairly clumsy, and I would suggest moving your palindrome logic to its own function.
Here is a refactored version of your program. This program discards the tails of overly long words ... but the buffer is reasonably large.
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 1024
FILE *open_file_or_die(const char *path, const char *mode)
{
FILE *file = fopen(path, mode);
if (!path) {
perror(path);
exit(EXIT_FAILURE);
}
return file;
}
int is_palindrome(const char *word, size_t len)
{
for (size_t i = 0; i < len / 2; i++)
if (word[i] != word[len - i - 1])
return 0;
return 1;
}
int main(void)
{
/*
FILE *input = open_file_or_die("C:\\Users\\HP\\Desktop\\New folder\\file4.txt", "r");
FILE *output = open_file_or_die("C:\\Users\\HP\\Desktop\\New folder\\file 2.txt", "w");
*/
FILE *input = stdin;
FILE *output = stdout;
char buffer[BUFFER_SIZE];
size_t length = 0;
int ch = 0;
while (EOF != ch) {
ch = fgetc(input);
if (isspace(ch) || EOF == ch) {
buffer[length] = '\0';
if (length && is_palindrome(buffer, length)) {
fputs(buffer, output);
fputc('\n', output);
printf("<%s> is a palindrome.\n", buffer);
}
length = 0;
} else if (length < BUFFER_SIZE - 1)
buffer[length++] = ch;
}
/*
fclose(input);
fclose(output);
*/
}

How to replace a character in text file using C?

I need to read a text file (E3-5.txt), and search for character c1 to be replaced by c2.
This is my incomplete code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char c;
char c1 = 'm';
char c2 = 'a';
int i;
FILE* fp;
fp = fopen("C:\\E3-5.txt", "r+");
if (fp == NULL)
{
printf("File not found!");
return 0;
}
for(c = getc(fp); c != EOF; c = getc(fp))
{
if(c == 'm')
{
i = ftell(fp);
printf("\nPosition %d", i);
}
}
}
I am having trouble how to locate the position of c1 in the text and how to rewrite it.
Edit:
I used the code from the answer, but it didn't change the text.
This is the new code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
char c;
char c1 = 'm';
char c2 = 'a';
int i;
FILE* fp;
fp = fopen("C:\\E3-5.txt", "rb+");
if (fp == NULL)
{
printf("File not found!");
return 0;
}
else
{
for(c = getc(fp); c != EOF; c = fgetc(fp))
{
if(c == c1)
{
fseek(fp, -1, SEEK_CUR);
fputc(c2, fp);
}
else
{
return 0;
}
}
}
return 0;
}
The program returned 0 without writing anything in the text
Here you have a very naive one:
int freplace(FILE *f, char needle, char repl)
{
int result = 1;
int c;
if(f)
{
while((c = fgetc(f)) != EOF)
{
if(c == needle)
{
fseek(f, -1, SEEK_CUR);
fputc(repl, f);
//all I/O functions require error handling
}
}
}
return result;
}
getc() returns an int so you need to declare int c not char c to check for the EOF.
ftell() gets the location. Use fwrite() or fputc() to write to file at that location by setting with fseek().
Go to https://en.cppreference.com/w/c for reference. Lots of beginners fail to read all of the standard library functions, and some even reinvent the wheel.
You really don't want to directly manipulate a file. Ever. Doing so is just asking for data corruption. Instead, create a new file and move it when you're done. Also, it's a lot easier to write the code. You can do so with something like:
#include <stdio.h>
#include <unistd.h>
int
main(int argc, char **argv)
{
int c1 = argc > 1 ? argv[1][0] : 'm';
int c2 = argc > 2 ? argv[2][0] : 'a';
const char *path = argc > 3 ? argv[3] : "stdin";
FILE *in = argc > 3 ? fopen(path, "r") : stdin;
if( in == NULL ){
perror(path);
return 1;
}
FILE *out = stdout;
char tmp[1024] = ".tmpXXXXX";
char *outpath = "stdout";
if( argc > 3 ){
outpath = tmp;
int fd = mkstemp(tmp);
if( fd == -1 ){
perror("mkstemp");
return 1;
}
if( (out = fdopen(fd, "w")) == NULL ){
perror(tmp);
return 1;
}
}
int c;
while( (c = fgetc(in)) != EOF ){
if( c == c1 ){
c = c2;
}
if( fputc(c, out) == EOF ){
perror(outpath);
return 1;
}
}
if( argc > 3 ){
if( fclose(out) ){
perror(outpath);
return 1;
}
if( rename(outpath, path) ){
perror(path);
return 1;
}
}
return 0;
}
String replace
Just for completeness, here is a bit of code to replace a word in a file! This will replace a single character, so of course it answers the question and shows some useful examples.
This is also my first and only non-trivial golden program, written in May 1994! Although you can certainly find fault with it, it worked as intended and my co-workers and I used it many different ways for sysadmin-related tasks. Compiled on MS C/C++
#include <stdio.h>
#include <string.h>
#define err(e) {_fcloseall(); fprintf(stderr, \
"USAGE: chg source dest oldstr newstr\n%s\n",e); exit(1);}
main (int argc,char *argv[])
{
FILE *in,*out;
char buffer[200];
char *old,*new;
int i,j,k;
if (argc!=5)
err("invalid # of parameters");
if ((in=fopen(argv[1],"r"))==NULL)
err("Can't open source");
if ((out=fopen(argv[2],"w"))==NULL)
err("Can't open dest");
old=argv[3];
new=argv[4];
if (*old=='"')
old++;
if (*new=='"')
new++;
if (i=strlen(old) && old[i-1]=='"')
old[i-1]=0;
if (i=strlen(new) && new[i-1]=='"')
new[i-1]=0;
if (!*old)
err("Can't search for nothing!");
if (!*new)
err("Can't replace nothing!");
j=0;
while (!feof(in))
{
if ((buffer[j]=fgetc(in))==EOF)
break;
buffer[j+1]=0;
j++;
if (!old[j-1])
{
fprintf(out,new);
fputc(buffer[j-1],out);
j=0;
}
else if (_strnicmp(buffer,old,j))
{
fprintf(out,buffer);
j=0;
}
else if (j>195)
err("Internal error, buffer filled past 195");
}
}

Print the user input strings into a least sized user input files

Program should read list of filenames, open these files and put their handles in the array of structure, then read strings and print consecutive lines of strings to smallest files by using handles contained in array of structures.
My program puts data from all lines to only one file which is initially the smallest which is false because it should the one which is smallest with every time it prints data into the file. This is my program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
struct file_t
{
FILE* f;
int size;
}t[5];
void close_file(struct file_t* f) {
if (f == NULL || f->f == NULL) {
}
else {
fclose(f->f);
}
}
int open_file(struct file_t* f, const char* filename) {
if (f == NULL || filename == NULL) {
return 1;
}
FILE* fp;
fp = fopen(filename, "ab");
if (fp == NULL) {
return 2;
}
long int res = ftell(fp);
fclose(fp);
f->size = res;
f->f = fopen(filename, "ab+");
if (fp == NULL) {
return 2;
}
return 0;
}
struct file_t* find_min(const struct file_t* files, int size) {
if (files == NULL || size <= 0) {
return NULL;
}
int x = (files + 0)->size, i = 0, index = 0;
for (i = 0; i < size; i++) {
if ((files + i)->size <= x) {
x = (files + i)->size;
index = i;
}
}
return (struct file_t*)(files + index);
}
int main() {
puts("Input files' names:");
char tab[100];
int num = 0;
while(1==1){
if(fgets(tab, 100, stdin)==NULL||*tab=='\n'){
if (num == 0) {
printf("Couldn't open file");
return 4;
}
break;
}
int index=strlen(tab);
*(tab+index-1)='\x0';
if (strlen(tab) > 30) {
*(tab + 30) = '\x0';
}
if (open_file((t + num), tab) > 0) {
}
else {
num++;
}
}
if (num == 0) {
printf("Couldn't open file");
return 4;
}
char str[1000];
printf("Input text:");
*str = '\x0';
while (fgets(str, 1000, stdin)==NULL||*str!='\n') {
int index=strlen(str);
*(str+index-1)='\x0';
struct file_t* p = find_min(t, num);
fwrite(str, sizeof(char), strlen(str), p->f);
}
for (int i = 0; i < num; i++) {
close_file(t + i);
}
printf("File saved");
return 0;
}
There are some critical bugs that you need to resolve.
fseek(stdin, 0, SEEK_END) -- fseek normally only work on a disk file, or something reasonably similar. Please refer to this link Using fseek with a file pointer that points to stdin
As a matter of fact even fflush() won't work. fflush is something that is designed for flushing output streams, and its behavior with input streams is implementation-dependent. Please refer to this link for more details stdinflush
scanf("%[^\n]s", tab)
If you are using this in a loop or multiple times, only the first read will succeed. The reason being, the \n character is left out from the previous input, and as said earlier fflush() might not be successful in removing that \n. The further calls to scanf() will simply return without reading anything.
'\0x' If you are intending to use this as string terminator then this is not it. It is a multi-character constant with an integer value 120. Below is a vague test run
Code
#include <stdio.h>
int main()
{
if ('\0' == '\0x' )
printf("both are same\n");
printf("%d",'\0x');
}
Compilation Warnings
test.c: In function ‘main’:
test.c:5:14: warning: multi-character character constant [-Wmultichar]
5 | if ('\0' == '\0x' )
| ^~~~~
test.c:8:14: warning: multi-character character constant [-Wmultichar]
8 | printf("%d",'\0x');
| ^~~~~
Output
120
fseek(fp, 0, SEEK_END); ftell(fp); -- This should not be used to determine the file sizes. The behavior of the fseek() with SEEK_END is undetermined in the case of binary files. Please refer to this link Do not use fseek() and ftell() to compute the size of a regular file
Some Logic Errors
1) You should compute the file size every time in find_min() as it gets changed whenever you write data to the file.
2) fwrite()won't actually dump the data to file immediately. you need to call fflush().
After resolving the above issues, this is the modified code.
Code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <sys/stat.h>
struct file_t
{
FILE* f;
int size;
}t[5];
void close_file(struct file_t* f) {
if (f == NULL || f->f == NULL) {
}
else {
fclose(f->f);
}
}
int open_file(struct file_t* f, const char* filename) {
if (f == NULL || filename == NULL) {
return 1;
}
f->f = fopen(filename, "a");
if (f->f == NULL)
return 2;
struct stat statbuf;
fstat(fileno(f->f), &statbuf);
f->size = statbuf.st_size;
return 0;
}
struct file_t* find_min(const struct file_t* files, int size) {
if (files == NULL || size <= 0) {
return NULL;
}
struct stat statbuf;
fstat(fileno(files->f), &statbuf);
int x = statbuf.st_size, i = 0, index = 0;
for (i = 0; i < size; i++) {
fstat(fileno((files+i)->f), &statbuf);
if (statbuf.st_size < x) {
x = statbuf.st_size;
index = i;
}
}
return (struct file_t*)(files + index);
}
int main() {
puts("Input files' names:");
char tab[100];
int num = 0;
while(1){
int c;
while (1) {
c = getc(stdin);
if (c == EOF || c == ' ')
goto user_input;
if(c != '\n')
break;
}
tab[0] = c;
if (scanf("%[^\n]s", tab+1) == EOF)
break;
if (*tab == '\0') {
if (num == 0) {
printf("Couldn't open file");
return 4;
}
break;
}
if (strlen(tab) > 30) {
*(tab + 30) = '\0';
}
if (open_file((t + num), tab) > 0) {
}
else {
num++;
}
*tab = '\0';
}
user_input:
if (num == 0) {
printf("Couldn't open file");
return 4;
}
fflush(stdin);
char str[1000];
printf("Input text:\n");
*str = '\0';
while(1) {
int c;
while(1) {
c = getc(stdin);
if (c == EOF)
goto main_exit;
if (c != '\n')
break;
}
str[0] = c;
if (scanf("%[^\n]s", str+1) == EOF)
break;
struct file_t* p = find_min(t, num);
fwrite(str, sizeof(char), strlen(str), p->f);
fflush(p->f);
}
main_exit:
for (int i = 0; i < num; i++) {
close_file(t + i);
}
printf("File saved");
return 0;
}
Terminal Session
$ ./a.out
Input files' names:
test file1.txt
test file2.txt
' '(NOTE: Space character inputted before pressing enter.)
Input text:
this is
stackoverflow
File saved
test file1.txt
this is
test file2.txt
stackoverflow
Note for breaking from the first loop (Files input). You need to enter space and then press enter (You can tweak around this).
Where are you updating the file_t->size when you write into a file?
You are calling this:
fwrite(str, sizeof(char), strlen(str), p->f);
But after that you should do p->size += strlen(str) to update its size, otherwise all file sizes are set to initial values, and hence all strings get written to a single file.
As for getting garbage data, try printing the string you are reading from scanf in the while loop.
You are using scanf to read characters until '\n', but you are not reading the '\n' itself. You need a fseek(stdin, 0, SEEK_END); in that loop as well.
Finally, why are you using syntax like this:
(files + i)->size
When you can call it more cleanly like this:
files[i].size
You code is really hard to read because of this.

How to split a text file into multiple parts in c

What i need to do, is to take a file of n lines, and for every x lines, create a new file with the lines of the original file. An example would be this:
Original File:
stefano
angela
giuseppe
lucrezia
In this case, if x == 2, 3 file would be created, in order:
First file:
stefano
angela
Second FIle:
giuseppe
lucrezia
Third File:
lorenzo
What i've done so far is this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10
int getlines(FILE *fp)
{
int c = 0;
int ch;
do{
ch = fgetc(fp);
if(ch == '\n')
{
c++;
}
}while(ch != EOF);
fseek(fp, 0 , SEEK_SET);
return c;
}
int ix = 0;
void Split(FILE *fp, FILE **fpo, int step, int lines, int *mem)
{
FILE **fpo2 = NULL;
char * filename = malloc(sizeof(char)*64);
char * ext = ".txt";
char number[2];
for(int i = ix; i < *mem; i++)
{
itoa(i+1, number,10);
strcpy(filename, "temp");
strcat(filename, number);
strcat(filename, ext);
if(!(fpo[i] = fopen(filename, "w")))
{
fprintf(stderr, "Error in writing\n");
exit(EXIT_FAILURE);
}
}
char ch;
int c = 0;
do{
ch = fgetc(fp);
printf("%c", ch);
if(ch == '\n')
{
c++;
}
if(c >= step)
{
c = 0;
ix++;
if(ix >= *mem && (ix*step) <= lines)
{
*mem = *mem + 1;
fpo2 = realloc(fpo, sizeof(FILE*)*(*mem));
Split(fp, fpo2, step, lines, mem);
}
}
putc(ch, fpo[ix]);
}while(ch != EOF);
}
int main()
{
FILE * fp;
if(!(fp = fopen("file.txt", "r")))
{
fprintf(stderr, "Error in opening file\n");
exit(EXIT_FAILURE);
}
int mem = N;
int lines = getlines(fp);
int step = lines/N;
FILE **fpo = malloc(sizeof(FILE *)*N);
Split(fp, fpo, step, lines, &mem);
exit(EXIT_SUCCESS);
}
I'm stack with segmentation error, i couldn't find the bug doing
gdb myprogram
run
bt
I really appreciate any help.
EDIT:
I've changed some things and now it works, but it creates an additional file that contains strange characters. I need to still adjust some things:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 10
int getlines(FILE *fp)
{
int c = 0;
int ch;
do{
ch = fgetc(fp);
if(ch == '\n')
{
c++;
}
}while(ch != EOF);
fseek(fp, 0 , SEEK_SET);
return c;
}
int ix = 0;
void Split(FILE *fp, FILE **fpo, int step, int lines, int *mem)
{
FILE **fpo2 = NULL;
char * ext = ".txt";
for(int i = ix; i < *mem; i++)
{
char * filename = malloc(sizeof(char)*64);
char * number = malloc(sizeof(char)*64);
itoa(i+1, number,10);
strcpy(filename, "temp");
strcat(filename, number);
strcat(filename, ext);
if(!(fpo[i] = fopen(filename, "w")))
{
fprintf(stderr, "Error in writing\n");
exit(EXIT_FAILURE);
}
free(number);
free(filename);
}
char ch;
int c = 0;
do{
ch = fgetc(fp);
printf("%c", ch);
if(ch == '\n')
{
c++;
}
if(c >= step)
{
c = 0;
ix++;
if(ix >= *mem && ((ix-1)*step) <= lines)
{
*mem = *mem + 1;
fpo2 = realloc(fpo, sizeof(FILE*)*(*mem));
Split(fp, fpo2, step, lines, mem);
}
}
putc(ch, fpo[ix]);
}while(ch != EOF);
}
int main()
{
FILE * fp;
if(!(fp = fopen("file.txt", "r")))
{
fprintf(stderr, "Error in opening file\n");
exit(EXIT_FAILURE);
}
int mem = N;
int lines = getlines(fp);
int step = lines/N;
FILE **fpo = malloc(sizeof(FILE *)*N);
Split(fp, fpo, step, lines, &mem);
exit(EXIT_SUCCESS);
}
There are a few problems in your code. But first I think you need to fix the most important thing
int step = lines/N;
Here step is 0 if your input file has less than N lines of text. This is because lines and N both are integer and integer division is rounding down.
I won't fix your code, but I'll help you with it. Some changes I
suggest:
Instead of getlines, use getline(3) from the standard
library.
fseek(fp, 0 , SEEK_SET) is pointless.
In char * filename = malloc(sizeof(char)*64), note that
both arguments to malloc are constant, and the size is arbitrary.
These days, it's safe to allocate filename buffers statically,
either on the stack or with static: char filename[PATH_MAX].
You'll want to use limits.h to get that constant.
Similarly you have no need to dynamically allocate your FILE
pointers.
Instead of
itoa(i+1, number,10);
strcpy(filename, "temp");
strcat(filename, number);
strcat(filename, ext);
use sprintf(filename, "temp%d%s", i+1, ext)
get familiar with err(3) and friends, for your own convenience.
Finally, your recursive Split is -- how shall we say it? -- a nightmare. Your whole program
should be something like:
open input
while getline input
if nlines % N == 0
create output filename with 1 + n/N
open output
write output
nlines++

How to read data from a .csv file to a multidimentional array using c language?

In matlab we can do it using the code :
a= csvread('filename.csv');
But using C programming i used the following code but it doesnt works please help :
int main(){
int i,j,temp,m1=0,n=0;
//CSV file reading
int ch;
FILE *fp;
fp = fopen("filename.csv","r"); // read mode
if( fp == NULL )
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
while( ( ch = fgetc(fp) ) != EOF )
{printf("%d",ch);}
fclose(fp);
return 0;
}
mat[i][j] = ch;
int m1 = i;
int n = j;
}
Please help !
Ok this hasn't been extensively tested but it should read a csv file that has integer values and store them in an (n x m) matrix.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv){
//CSV file reading
int rowMaxIndex,columnMaxIndex;
int **mat;
int *matc;
int i,j,idx;
char part[1024];
char *token;
FILE *fp;
fp = fopen("filename.csv","r"); // read mode
if(fp == NULL){
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
// count loop
rowMaxIndex = 0;
columnMaxIndex = 0;
while(fgets(part,1024,fp) != NULL){
token = NULL;
while((token = strtok((token == NULL)?part:NULL,",")) != NULL){
if(rowMaxIndex == 0){ // only want to increment column count on first loop
columnMaxIndex++;
}
for(idx = 0;idx<strlen(token);idx++){
if(token[idx] == '\n'){ // this assumes there will be a \n (LF) at the end of the line
rowMaxIndex++;
break;
}
}
}
}
// allocate the matrix
matc = malloc(rowMaxIndex*columnMaxIndex*sizeof(int));
mat = malloc(rowMaxIndex*sizeof(int*));
for(idx = 0;idx<rowMaxIndex;idx++){
mat[idx] = matc+idx*columnMaxIndex;
}
// rewind the file to the beginning
rewind(fp);
// read loop
i = j = 0;
while(fgets(part,1024,fp) != NULL){
token = NULL;
while((token = strtok((token == NULL)?part:NULL,",")) != NULL){
mat[i][j] = atoi(token);
j = (j+1)%columnMaxIndex;
}
i++;
}
fclose(fp);
return 0;
}

Resources