#include <stdio.h>
#include <stdlib.h>
int main ( int argc, char *argv[] )
{
//sets the number of lines ot be read
char strline[10000];
// checks to see that there are only 2 entries in the argv by checking in argc
if ( argc != 2 )
{
printf( "ERROR. Enter a file name\n", argv[0] );
}
else
{
//opens the file which was entered by the user as read only
FILE *infile = fopen( argv[1], "r");
// covers a miss spelling of a file name or file doesn't exist
if ( infile == 0 )
{
printf( "ERROR. Did you make a mistake in the spelling of the file or the File entered doesn't exist\n" );
}
else
{
// File exists read lines, while not at the end of the file
while (!feof(infile))
{
//Get next line to be printed up to 126 characters per a line
if(fgets(strline, 126, infile))
{
//print the current line (stored in strline)
printf("%s",strline);
}
}
//closes the file
fclose( infile );
return 0;
}
}
}
On the 6th line (comment above) I have stated this is the maximum amount of lines the program can read. I was informed yesterday that this isn't the case.
Can someone explain to me what the code line actually means?
char strline[10000];
So from what people have being saying what setting it to 128 make more snese (126 for fgets and some room)
char strline[10000]; neans you have allocated a buffer that is 10,000 bytes long:
+--------------...-+
strline -> | 10000 |
+--------------...-+
if you wanted to allocate for 10,000 lines instead you would need something like this:
char* strline[10000]; // array of 10,000 pointers to strings
accessing lines would be to assign to each entry in the array
strline[0]
strline[1]
...
strline[10000]
like when a line is read you would need to allocate a buffer for the line and then point to it from strline
char* line = malloc( linelength + 1 );
fgets( line, linelength, fp );
strline[0] = line;
+-------+
strline[0] -> | line |
+-------+
Related
I am writing a text file parser in C.
I would like to read each line of a text file using fgets, except for the very last line, which I would like to skip.
Also, there is no telling how many characters will be in the file or in the last line, but assume my parser only cares about the first LINEMAXLEN characters in each line.
Currently, the only way I can think to do this is by running two loops, something like the following:
char line[ LINEMAXLEN+1u ];
unsigned int nlines;
unsigned int i;
nlines = 0u;
while ( fgets (line, LINEMAXLEN, file) != NULL )
nlines += 1u;
i = 0u;
while ( fgets (line, LINEMAXLEN, file) != NULL ) {
if ( i >= nlines - 1u )
break;
//...parse the line
i += 1u;
}
But surely, there's got to be a smarter way to do it in only one loop, no?
Instead of using two loops, it would be more efficient to always read two lines in advance and to only process a line once the next line has been sucessfully read. That way, the last line will not be processed.
Here is an example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define LINEMAXLEN 30
//forward function declarations
void process_line( const char *line );
bool read_start_of_line_and_discard_rest( char buffer[], int buffer_size, FILE *fp );
int main( void )
{
FILE *fp;
char lines[2][LINEMAXLEN];
//This index specifies which index in the array "lines"
//represents the newest line. The other index is the
//index of the previous line.
int newest_index = 0;
//attempt to open file
fp = fopen( "input.txt", "r" );
if ( fp == NULL )
{
fprintf( stderr, "Error opening file!\n" );
exit( EXIT_FAILURE );
}
//read first line
if ( !read_start_of_line_and_discard_rest( lines[newest_index], LINEMAXLEN, fp ) )
{
fprintf( stderr, "Error reading first line!\n" );
exit( EXIT_FAILURE );
}
//process one line per loop iteration
for (;;)
{
//swap the index, so that the newest line is now the
//previous line
newest_index = !newest_index;
//read the new line
if ( !read_start_of_line_and_discard_rest( lines[newest_index], LINEMAXLEN, fp ) )
{
//we have reached end-of-file, so we don't process the
//previous line, because that line is the last line
break;
}
//since reading in a new line succeeded, we can be sure that
//the previous line is not the last line, so we can process
//the previous line
//process the previous line
process_line( lines[!newest_index] );
}
//cleanup
fclose( fp );
}
//This function will process a line after it has been read
//from the input file. For now, it will only print it.
void process_line( const char *line )
{
printf( "Processing line: %s\n", line );
}
//This function will read exactly one line of input and remove the
//newline character, if it exists. On success, it will return true.
//If this function is unable to read any further lines due to
//end-of-file, it returns false. If it fails for any other reason, it
//will not return, but will print an error message and call "exit"
//instead.
//If the line is too long to fit in the buffer, it will discard
//the rest of the line and report success.
bool read_start_of_line_and_discard_rest( char buffer[], int buffer_size, FILE *fp )
{
char *p;
//attempt to read one line from the stream
if ( fgets( buffer, buffer_size, fp ) == NULL )
{
if ( ferror( fp ) )
{
fprintf( stderr, "Input error!\n" );
exit( EXIT_FAILURE );
}
return false;
}
//determine whether line was too long for input buffer
p = strchr( buffer, '\n' );
if ( p == NULL )
{
int c;
//discard remainder of line
do
{
c = getchar();
} while ( c != EOF && c != '\n' );
}
else
{
//remove newline character by overwriting it with a null
//character
*p = '\0';
}
return true;
}
For the input
This is line1.
This is line2 which has an additional length longer than 30 characters.
This is line3.
This is line4.
this program has the following output:
Processing line: This is line1.
Processing line: This is line2 which has an ad
Processing line: This is line3.
As you can see, all lines except the last line are being processed, and only the first LINEMAXLEN-1 (30-1 in my example) characters of each line are being processed/stored. The remaining characters are being discarded.
Only LINEMAXLEN-1 instead of LINEMAXLEN characters from each line are being processed/stored because one character is required to store the terminating null character.
This is quite simple to do in a single loop if we use alternating buffers [as others have mentioned].
In the loop below we read a line into the "current" buffer. If not the first line, we process the previous line in the "other" buffer.
By alternating the index into a buffer pool of two buffers, we avoid unnecessary copying.
This introduces a delay in the processing of the buffer. On the last iteration, the last line will be in the current buffer, but it will not be processed.
#define LINEMAXLEN 1000 // line length of buffer
#define NBUF 2 // number of buffers
char lines[NBUF][LINEMAXLEN]; // buffer pool
int previdx = -1; // index of bufs for _previous_ line
int curidx = 0; // index of bufs for _current_ line
char *buf; // pointer to line buffer to process
// read all lines into alternating line buffers
for (; fgets(lines[curidx],LINEMAXLEN,stdin) != NULL;
previdx = curidx, curidx = (curidx + 1) % NBUF) {
// process _previous_ line ...
if (previdx >= 0) {
buf = lines[previdx];
// process line ...
}
}
fgets() will not modify the buffer at all when it reaches EOF, so just read lines until fgets() returns NULL. The last line read will be retained:
#include <stdio.h>
int main( int argc, char **argv )
{
char line[ 1024 ];
FILE *f = fopen( argv[ 1 ], "r" );
if ( NULL == f )
{
return( 1 );
}
for ( ;; )
{
char *p = fgets( line, sizeof( line ), f );
if ( NULL == p )
{
break;
}
}
printf( "last line: %s\n", line );
return( 0 );
}
This relies on the required behavior of fgets():
The fgets function returns s if successful. If end-of-file is encountered and no characters have been read into the array, the contents of the array remain unchanged and a null pointer is returned.
Robust code should check for errors with ferror().
Working that into your text processing is left as an exercise... ;-)
I've tried multiple stuff as reading new lines after checking if that columns is "General" but still does not work at all. It is an csv file and it would be lines with commas after each fgets and i need a specific column with it's data.
Here's my code:
char fi[1024];
while(!feof(CsvFile)){
//Read
fgets(fi, 1024, CsvFile);
if(strstr(fi, "General") == 0){
fscanf(CsvFile, "%[^\n]s", fi);
printf("%s", fi);
}
fgetc(CsvFile);
}
It does not print what i want.
Reading a CSV file is much more complicated than you assumed (see https://www.rfc-editor.org/rfc/rfc4180). You must take all kind of rules into account. For instance, if a cell contains a comma, the content must be surrounded by ".
However, you can implement a simplified version which assumes:
a CSV file is made of lines;
a line is MAX_LINE characters, at most;
a line is made of cells;
a cell ends with comma or new-line;
a cell contains anything but comma or new-line.
The code below reads one line at a time and then uses strtok to split the line into cells.
Welcome to SO and good luck!
#include <stdio.h>
#include <string.h>
#define MAX_LINE 1024
int main( int argc, char* argv[] )
{
//
FILE* fp = fopen( "c:\\temp\\so.txt", "r" );
if ( !fp )
{
printf( "could not open file" );
return -1;
}
//
char line[ MAX_LINE + 1 ];
while ( fgets( line, sizeof( line ) / sizeof( *line ), fp ) ) // get a line
{
int col_idx = 0;
const char* sep = "\r\n,"; // cells are separated by a comma or a new line
char* cell = strtok( line, sep ); // find first cell
while ( cell )
{
// your processing code goes here
cell = strtok( NULL, sep ); // next cell
col_idx++;
}
}
return 0;
}
I'm given a text file containing information about a game world and it's collision data in this format.
Width 5
Height 5
10001
11000
11100
11111
11111
To store the data, I'm given
static int BINARY_MAP_WIDTH;
static int BINARY_MAP_HEIGHT;
and
static int **MapData; // Dynamic array of map data
My FileIO knowldege doesn't go much beyond reading in strings from a file line by line.
So far I have this very roundabout way of reading in just the first two lines.
FILE *Data;
int line = 1; // line number that we're on
Data = fopen(FileName, "rt");
if (!Data)
return 0;
if (Data)
{
while (!feof(Data))
{
if (line == 1)
fscanf(Data, "%*[^0-9]%d%n", &BINARY_MAP_WIDTH);
if (line == 2)
fscanf(Data, "%*[^0-9]%d%n", &BINARY_MAP_HEIGHT);
if (line > 2)
break;
line++;
}
}
And to be quite honest, I'm not entirely sure why it's working, but I am getting the correct values into the variables.
I know how to set up the dynamic array, at this point my issue is with reading in the correct values.
I'm not sure where to go from here.
Here's a couple things you need to know about fscanf
fscanf will consume as many bytes as necessary to perform the
requested conversions and will update the file pointer accordingly.
The next call to fscanf will start at the location in the file
where the previous fscanf ended.
fscanf returns the number of successful conversions, so you
should verify that the return value is equal to the number of
conversions requested.
So here's how I would rewrite the code you have so far
#include <stdio.h>
static int mapWidth;
static int mapHeight;
int readFromFile( char *name )
{
FILE *fp;
int good = 1;
if ( (fp = fopen(name, "r")) == NULL )
return 0;
if ( fscanf(fp, "%*[^0-9]%d", &mapWidth) != 1 )
good = 0;
if ( fscanf(fp, "%*[^0-9]%d", &mapHeight) != 1 )
good = 0;
if ( good )
{
// the code to read the rest of the file goes here
}
fclose( fp );
return good;
}
int main( void )
{
if ( readFromFile( "input.txt" ) )
printf( "%d %d\n", mapWidth, mapHeight );
else
printf( "readFromFile failed\n" );
}
The next step is to figure out
how to allocate memory for MapData based on the width and height
how to read the rest of the lines in a loop, e.g. using fgets or fscanf(..."%s"...)
how to parse those lines to fill in the MapData
I'm really new to C, so sorry if this is a dumb question but let's say I have a file containing the following:
1 abc
2 def
3 ghi
If I pass in an integer like 3 (Or character?) the function will return a string of "ghi". I don't know how to make this happen.
void testFunc(int num)
{
FILE *fp;
fp = fopen("testfile.txt", "r");
if(strstr??????
}
Yea.. I have no idea what I'm doing. Can anybody offer any guidance?
You can follow this link, you can do a bit google also.
Its really simple you should try your own once.
Reading c file line by line using fgetc()
Use fgets to read each line
Use sscanf to save the first and second elements of each line to variables
Test whether the number = 3, and if so print the word.
The man pages should give you all the info you need to use fgets and sscanf
Try this code
void testFunc(int num)
{
FILE *file = fopen ( "testfile.txt", "r" );
char line [ 128 ]; /* or other suitable maximum line size */
if ( file != NULL )
{
while ( fgets ( line, sizeof(line), file ) != NULL ) /* read a line */
{
fputs ( line, stdout ); /* write the line */
}
fclose ( file );
}
}
//input:num, output:string, string is call side cstring area.
void testFunc(int num, char *string){
FILE *fp;
int n;
fp = fopen("data.txt", "r");
while(2==fscanf(fp, "%d %s ", &n, string)){
if(num == n){
printf("%s\n",string);
break;
}
}
fclose(fp);
return;
}
I am just not sure why my replaceWord isn't going in to the file at all i have used all the commented out and so on and so forth. I am just trying to replace with with the text received from the command line argument. I know i might be far off I was just looking for a relatively easy way to do it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ( int argc, char *argv[] )
{
if ( argc != 4 ) /* argc should be 2 for correct execution */
{
/* We print argv[0] assuming it is the program name */
printf( "usage: %s filename\n", argv[0] );
}
else
{
// We assume argv[1] is a filename to open
char* wordReplace = argv[1];
char* replaceWord = argv[2];
FILE *file = fopen( argv[3], "r" );
/* fopen returns 0, the NULL pointer, on failure */
if ( file == 0 )
{
printf( "Could not open file\n" );
}
else
{
char string[100];
int len = 0;
/* read one character at a time from file, stopping at EOF, which
indicates the end of the file. Note that the idiom of "assign
to a variable, check the value" used below works because
the assignment statement evaluates to the value assigned. */
while ( (fscanf( file, "%s", string ) ) != EOF )
{
len = strlen(string);
printf( "%s\n", string );
if(strcmp(string, wordReplace) == 0){
//fseek (file, (-strlen(string) + 1), 1);
//fputc(*replaceWord,file);
//replaceWord++;
//strcpy(string, replaceWord);
fprintf(file,"%s",replaceWord);
fputs(replaceWord, file);
printf("\n%d\n", len);
}
}
fclose( file );
}
}
printf("\n");
return 0;
}
You've opened the file in r ie read mode and trying to write to it.
Also after correcting that, note that, the replaced word and word to be replaced have to be of the same size, if you want to replace the file in place. Else you will end up overwriting other data. And you need to use functions like fseek to reposition the internal file pointer as fp would have moved ahead after fscanf