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>
Related
I'm attempting to print an array of structures read from a CSV file in Excel. However, only the students' IDs are printed; other information was also printed but some confusing rare characters. Can you please tell me what could be wrong with this code?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student {
char ID[8];
char name[32];
int score;
} student;
int main(int argc, char *argv[]) {
student student_list[100];
FILE *source = fopen("students.csv", "r");
if (source == NULL) {
perror("Unable to open the source file.");
exit(1);
}
char buffer[1024];
fgets(buffer, sizeof(buffer), source);
int num_student = 0;
while (!feof(source)) {
student *one_student = student_list + num_student;
sscanf(buffer, "%8[^,] %32[^,] %3[^,]",
&one_student->ID, &one_student->name, &one_student->score);
fgets(buffer, sizeof(buffer), source);
num_student++;
}
for (int i = 0; i < num_student; i++) {
printf("ID: %s name: %-9s score: %-3d\n",
student_list[i].ID, student_list[i].name, student_list[i].score);
}
fclose(source);
return 0;
}
This is a sample input file students.csv:
B213350,John Adam Smith,80
B191835,Mary Elizabeth Smith,71
B201304,Yamazaki Fuyumi,95
B201832,Liam,57
B201834,Alfonso Hernández,65
There are multiple problems:
you should not use feof(). Read Why is “while ( !feof (file) )” always wrong?
Use this loop instead:
while (fgets(buffer, sizeof buffer, source)) {
// handle the line
}
the sscanf() format string is incorrect: the character counts are too large and the , are missing. It should be " %7[^,\n], %31[^,\n], %d" and you should check that the return value is 3, the number of successful conversions expected.
you should stop when the student array is full.
Here is a modified version:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student {
char ID[8];
char name[32];
int score;
} student;
int main(int argc, char *argv[]) {
student student_list[100];
FILE *source = fopen("students.csv", "r");
if (source == NULL) {
fprintf(stderr, "Cannot open file students.csv: %s\n", strerror(errno));
return 1;
}
char buffer[1024];
int num_student = 0;
while (num_student < 100 && fgets(buffer, sizeof(buffer), source)) {
student *one_student = &student_list[num_student];
if (sscanf(buffer, " %7[^,\n], %31[^,\n], %d",
one_student->ID, one_student->name,
&one_student->score) == 3) {
num_student++;
} else {
printf("invalid CSV line: %s", buffer);
}
}
for (int i = 0; i < num_student; i++) {
printf("ID: %-9s name: %-32s score: %-3d\n",
student_list[i].ID, student_list[i].name,
student_list[i].score);
}
fclose(source);
return 0;
}
Note that this approach to parsing CSV files cannot handle empty fields. Parsing the line with strtok() would not work either because consecutive commas would be handled as a single separator. You need a different approach using strcspn() or strchr().
I'm trying to make a random input.txt file generator in C language but I keep getting random characters in the output file. I tried using both putw() and fwrite() but I get the same result.
for(int i = 0; i < 100; i++){
ran_numb = rand()%(ram_size-1);
// printf("%d", ran_numb);
// int err = putw(ran_numb, fp);
fwrite(&ran_numb, sizeof(int), 1, fp);
fputc('\n', fp);
}
output file:
~
ô
u
?
{
ø
È
Õ
å
×
¡
full code:
#include <stdio.h>
#include <string.h>
int main (int argc, char* argv){
generate_input_file(2048);
}
void generate_input_file(int ram_size){
int ran_numb = 0;
FILE *fp = fopen("input.txt", "w");;
if(fp == NULL){
printf("can't open file!");
}
for(int i = 0; i < 100; i++){
ran_numb = rand()%(ram_size-1);
// printf("%d", ran_numb);
// int err = putw(ran_numb, fp);
fwrite(&ran_numb, sizeof(int), 1, fp);
fputc('\n', fp);
}
}
After the help of the comments, this is the final program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
#include "simulator.h"
int main (int argc, char* argv){
generate_input_file(2048);
}
void Gen_Input_File(int ram_size){
int ran_numb = 0;
const char filename[] = "input.txt"
FILE *fp = fopen(filename, "w");;
if(fp == NULL){
fprintf(stderr, "Failed to open file '%s' for writing: %s\n", filename, strerror(errno));
exit(EXIT_FAILURE);
}
srand(time(NULL));
for(int i = 0; i < 10000; i++){
ran_numb = rand()%(ram_size-1);
fprintf(fp, "%d\n", ran_numb);
}
}
I've added the missing headers to stop warnings.
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;
}
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).
#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;
}