How to ignore multiple inputs when reading from a file? - c

So currently I have this code that allows me to import words from a text file and store it in to an array, what I would like it to do is ignore any punctuation such as "," - "." - etc.
However I am unable to do so with %[,]s or something similar seen below, any help on this please?
#include <stdio.h>
#include <string.h>
int main()
{
FILE *myFileHandle;
myFileHandle = fopen("test1.txt", "r");
char *lineofText;
if (myFileHandle != NULL){
while (!feof(myFileHandle)){
fscanf(myFileHandle, "%[,]s", lineofText);
puts(lineofText);
}
}
fclose(myFileHandle);
}
Thanks.

Related

fscanf returning suspicious data in C

Here is the website of the data files: Group Data Release
And here I am using the catalogs of SDSS_MTV (the third section from the bottom of the webpage).
The data are split into 8 parts. I am trying to read one of these files (such as "Fillingfactor_sdssMth12_80Mpc").
Actually, I am using fscanf() to get the data of "Fillingfactor_sdssMth12_80Mpc". Some of them show the values far greater than 1, that's unreasonable because the filing factor cannot exceed 1.
Here is the excerpt of this file (the first 5 rows):
609d 6c34 417e edb0 2664 0231 4452 3931
d948 2bb2 d877 15b2 0f5b e4b1 b646 9631
470e e3b1 06e2 3fb2 3483 f4b1 2c3d 11b2
6d86 89b1 8135 04b2 005c 44b2 d9eb a4b0
ad80 04b2 8dfb fcb1 03b0 3d32 afc6 4432
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main()
{
int i;
int Nx,Ny,Nz,itemp;
FILE *fp;
char filename[256];
sprintf(filename,"Fillingfactor_sdssMth12_80Mpc");
Nx=494;
Ny=892;
Nz=499;
float *quan = (float *)malloc(Nx*Ny*Nz*sizeof(float));
fp = fopen(filename,"r");
fread(&itemp,1,sizeof(float),fp);
// Checks the length of the table.
printf("itemp = %i\n", itemp);
if(itemp/sizeof(float) != Nx*Ny*Nz)
{
printf("error! itemp=%d\n",itemp);
exit(1);
}
for(i=0;i<Nx*Ny*Nz;i++)
{
fscanf(fp,"%f",&quan[i]);
printf("grid %i is: %.4lf\n", i, quan[i]);
}
fclose(fp);
}
Could someone explain me what is wrong?

C - Reading CSV file in char array

I have a very little experience in C programming, particularly File Handling. I am developing a project in which I'm supposed to create a Sign Up/Log In system. I have a .csv file in which the data are separated by ,
What I am trying to do is reading the first and second column into two char arrays respectively.
char userLogin[100];
char userPassword[100];
FILE *file3 = fopen("C:\\Users\\Kshitiz\\Desktop\\BAAS\\signup_db.csv","r");
if(file3 != NULL){
while(!feof(file3)){
fscanf(file3,"%[^,],%s",userLogin,userPassword);
puts(userLogin);
puts(userPassword);
}
}
fclose(file3);
Content of signup_db.csv:
Username,Password
SBI063DDN,Qazwsx1234
ICICIDDN456,WSXEDC1234r
Expected Output:
Username
Password
SBI063DDN
Qazwsx1234
ICICIDDN456
WSXEDC1234r
Output which I'm getting:
Username
Password
SBI063DDN
Qazwsx1234
ICICIDDN456
WSXEDC1234r
WSXEDC1234r
Can anyone please help me how can I resolve this issue? Thank you!
The 'fscanf()' function returns the number of items of the argument list successfully filled. So instead try this:
while(fscanf(file3,"%[^,],%s",userLogin,userPassword) == 2)
{
puts(userLogin);
puts(userPassword);
}
The problem you mentioned is probably because of a new line character at the end of your file. When you read the last line, you have not yet reached the end of file. The above code solves this issue.
In my case I have the expected results, but I don't know if there is a difference with the compiler or if my csv file is different (I've tried to recreate it). Here is another way to parse the file, check if you have the expected results:
#include <stdio.h>
#include <string.h>
#define LINE_LENGTH 1000
int main(void) {
char userLogin[100];
char userPassword[100];
char line[LINE_LENGTH];
char *delimiter = ",";
char *token;
FILE *file3 = fopen("signup_db.csv", "r");
while(fgets(line, LINE_LENGTH, file3) != NULL) {
token = strtok(line, delimiter);
printf("%s\n", token);
token = strtok(NULL, delimiter);
printf("%s\n", token);
}
fclose(file3);
}

read from file line by line, write random lines to another file in C

So i have a file with multiple lines on it, and I want to copy some of those line to a new file, random lines to be specific.
Everything goes fine as long as I copy all the lines file from file, but when I try to introduce randoming, in the new file the lines misses couple characters
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <malloc.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
srandom(time(NULL));
int n,i=0,j=0,k,l;
char c[200][200];
char *buff=(char *)malloc(sizeof(char));
int f= open("erzekelokbeugro.txt",O_RDONLY);
int f2= open("teszt.txt",O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
do
{
do
{
n=read(f,buff,1);
c[j][i]=*buff;
//printf("%c",buff[0]);
i++;
}
while(buff[0] !='\n');
j++;
}
while(n>0);
k=10;
//j=73;
i=0;
while(k>0)
{
j=rand()%49;
//printf("%d ", j);
do
{
*buff=c[j][i];
if(buff[0]!=0)
{
write(f2,buff,1);
//printf("%c",buff[0]);
}
i++;
}
while(buff[0] !='\n');
//printf("----\n");
k--;
}
close(f);
close(f2);
return 0;
}
The input is someting like this (i wont copy the whole file, just a sample, its in hungarian, but the content doesnt matter anyway):
8.Érzékelés alsó határa (detektálási küszöb)
9.Felbontás
10.Nullponteltolódás (drifft)
11.Érzékenység eltolódás
12.Ismétlési (reprodukciós) hiba
13.Csereszabatosság mértéke
14.Szelektivitás
15.Beállási idő
16.Élettartam
17.Hőmérséklet definíciója
18.Mit tud a Celsius skáláról:
19.Ismertesse a hőmérsékleti együttható (?) képletét az ellenállás-hőmérő esetén.Nevezze meg a képlet elemeit.
and the output is like this:
és voltmérő sematikus ábrája
5.Linearitás
as műszerek működési elve:
15.Beállási idő
26.Ismertesse a nyomás definícióját, és kiszámítási képletét.
28.Villamos elvű passzív nyomásmérő főbb típusai
34.Ellenállás nyomásérzékelő mérési tartománya és pontossága
29.A villamos elvű nyomásmérők előnyei
35.Piezoelektromos nyomásérzékelés mérési elve
ust használó szenzorok előnyei:
As you can see, all the line should start with a number, but sometimes its missing, also some character (even half a line), but the next goes fine
i needs to be initialized each time you pick a new j. You might also want to look into how to print a whole string at once, instead of doing it a character at a time.

Specific data from txt file using C

Hello i have a text file that contains cities, dates and temperature. How can i read temperature from specific city and day? For example if I search for Alingsås 2014-05-14 I need to get 13.81, 11.59 and 13.81. The part I am stuck with is after i have opened the file and put variables for the city and date. Info is stored in the text file like this:
Alingsås;
2014-05-14;
13.81;
11.59;
13.81;
2014-05-15;
8.89;
7.99;
9.15;
2014-05-16;
6.2;
5.07;
6.58;
2014-05-17;
7.91;
5.55;
7.91;
2014-05-18;
7.76;
5.95;
7.76;
2014-05-19;
7.95;
6.91;
9.72;
2014-05-20;
18.45;
12.92;
18.45;
Arboka;
2014-05-14;
9.55;
4.53;
10.66;
2014-05-15;
6.33;
1.5;
9.37;
2014-05-16;
8.85;
3.4;
12.08;
2014-05-17;
14.01;
4.8;
15.4;
2014-05-18;
14.16;
6.35;
17.23;
2014-05-19;
21.39;
14.57;
21.39;
2014-05-20;
23.34;
14.82;
23.34;
My Code so far is
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <locale.h>
#include <string.h>
int main(void)
{
FILE * fp;
char c;
// open file
fp =fopen("C:\\Users\\Karl\\Desktop\\info.txt", "r");
if (fp != NULL)
{ char city[10] = "Ålingsås";
int temp1;
int temp2;
int temp3;
char date[13] = "2014-05-14";
One solution is to make a structure that contains the name of the city, and a pointer to another structure which will be an "array" (dynamically allocated on the heap) and where each entry contains the data and the three temperatures.
Then read one line at a time from the file, trim the input (to remove the leading and trailing whitespace, if there is any) and create the above structure. If the current line starts with a digit it's a date and read three more lines for the temperature and fill in the structure. If the current line doesn't start with a digit then you have a new city, and you create a new city-structure.

How to remove the path to get the filename

How does one remove the path of a filepath, leaving only the filename?
I want to extract only the filename from a fts_path and store this in a char *fileName.
Here's a function to remove the path on POSIX-style (/-separated) pathnames:
char *base_name(const char *pathname)
{
char *lastsep = strrchr(pathname, '/');
return lastsep ? lastsep+1 : pathname;
}
If you need to support legacy systems with odd path separators (like MacOS 9 or Windows), you might need to adapt the above to search for multiple possible separators. For example on Windows, both / and \ are path separators and any mix of them can be used.
You want basename(3).
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <libgen.h>
int main(void)
{
char * path = "/homes/mk08/Desktop/lala.c";
char * tmp = strdup(path);
if(tmp) {
printf("%s\n", basename(tmp));
free(tmp);
}
return EXIT_SUCCESS;
}
This will output:
lala.c
I'm sure there is a less roundabout way of doing this, but you could always search through the filepath (I assume it is stored as a char array?), get the position of the final '\', and then erase everything prior to that.
Edit: See R's comment.

Resources