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;
}
Related
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
This question already has answers here:
Reading the whole text file into a char array in C
(5 answers)
Closed 8 years ago.
I wrote c code which input value for my program comes from here :
char *input[] = {"This input string value !!!", NULL};
But how can I read this value from the file (e.g. input.txt)? Is it possible to get the file content like a string?
Thanks a lot!
If you want to read a file line-by-line, the easiest way to go is using getline. Read the man page for a detailed description and a good code example.
getline will do all the low-lvel plumbing work of allocating buffers, copying data and scanning for newline characters, etc for you. Keep in mind that this is only possible since getline uses dynamically allocated memory that you'll need to free again.
On recent Posix compliant systems you could use getline(3), something like
FILE *fil = fopen("somefile.txt", "r");
if (!fil) {perror("somefile.txt"); exit(EXIT_FAILURE); };
char*linbuf = NULL;
size_t siz = 0;
ssize_t linlen = 0;
while ((linlen=getline(&linbuf, &siz, fil))>0) {
// linbuf contains the current line
// linlen is the length of the current line
do_something_with(linbuf, linlen);
};
fclose(fil);
free(linbuf), linbuf=NULL;
linlen = 0, siz = 0;
You can use fgets() like this:
#include <stdio.h>
int main(void)
{
char buffer[100];
FILE *file = fopen("input.txt", "r");
// Checks if the file was opened successfully
if (file == NULL)
{
fputs("Failed to open the file\n", stderr);
return -1;
}
// fgets here reads an entire line or 99 characters (+1 for \0) at a time, whichever comes first
while (fgets(buffer, sizeof(buffer), file) != NULL)
{
printf("Line read = %s\n", buffer);
}
fclose(file);
}
You can also use fgetc() like this:
#include <stdio.h>
int main(void)
{
int ch;
FILE *file = fopen("input.txt", "r");
// Checks if the file was opened successfully
if (file == NULL)
{
fputs("Failed to open the file\n", stderr);
return -1;
}
// fgetc reads each character one by one until the end of the file
while ((ch = fgetc(file)) != EOF)
{
printf("Character read = %c\n", ch);
}
fclose(file);
}
search the site but did not find this kind of question
i have a short txt file (Ini)
in it there will be config in this kind of pattern
blabla= 1111
kaka= 2313
blublu = 1
the problem in the way i wrote the code it find the pattern only if it in the first line
i tried this
int number;
FILE *Config;
char ch_theconfig[1000];
Config = fopen("config.ini","r");
size_t sizeofConfig = fread(ch_theconfig, 1, 1000, Config);
sscan(ch_theconfig,"kaka= %d",&number);
how do it make it look even after a new line?
thX for the help!!
****edit
is there no way to find pattern in full file without checking line by line?
or is there a way to make it to a new string who will be without the \n from the origenal file?
again thx
#include <stdio.h>
#include <string.h>
int main(){
int number;
FILE *Config;
char ch_theconfig[0x1000], *p;
Config = fopen("data.txt","r");
size_t sizeofConfig = fread(ch_theconfig, sizeof ch_theconfig, 1, Config);
if(p=strstr(ch_theconfig, "kaka=")){//"kaka ="?
sscanf(p + 5,"%d", &number);//5 : strlen("kaka="),
printf("kaka=%d\n", number);
}
fclose(Config);
return 0;
}
1.Use fscanf() in a while loop until the EOF character is detected.
2.Else if you want to read line by line use this
while ((read = getline(&line, &len, Config)) != -1) {
printf("length %zu :\n", read);
printf("%s", line);
}
PS I haven't declared the variables but they are self explanatory
3 Or use fgets() as follows
while ( fgets ( line, sizeof line, Config ) != NULL ) /* read a line */
{
fputs ( line, stdout ); /* write the line */
}
Newline is also a character in file so you need to read and discard it to proceed to the next input in file. you can read it as character %c into some variable.
i have a c project and i have serious problem , i want to open file and replace line number nb (nb is an int) with "*" . this is my code could some one help me please ? it show me the word i want to replace that's mean that the pointer is pointing on the wanted line but nothing happen .help me please
#include <stdio.h>
int main( void )
{
FILE * f;
char ch[1024];
int i, nb;
i = 0;
scanf( "%d", &nb ) ;
f = fopen( "dict.txt", "r+t" );
while( i < nb )
{
fscanf( f, "%s", ch ) ;
i++;
}
printf( "%s", ch );
fprintf( f, "%s", "****" );
fclose( f );
}
You've opened the file for reading and writing. According to the MSDN man page for fopen (I am assuming from the r+t mode on the file that you are using Visual Studio):
When the "r+", "w+", or "a+" access type is specified, both reading and writing are allowed (the file is said to be open for "update"). However, when you switch from reading to writing, the input operation must encounter an EOF marker. If there is no EOF, you must use an intervening call to a file positioning function. The file positioning functions are fsetpos, fseek, and rewind.
Some other things to keep in mind:
When fscanf reads a string with %s, it reads only one word at a time, not a whole line. It is easier to read whole lines of input with fgets than with fscanf.
A file consists of a stream of bytes. If the line you want to replace is 47 characters long, then fprintf(f, "%s", "****") will only replace the first four bytes in the line.
That means that if you want to replace line #nb, you will need to read in the line, figure out how long it is, then seek back to the beginning of the line and print out the correct number of asterisks.
Try something like this instead:
#include <stdio.h>
#include <string.h>
int main()
{
FILE * f;
char ch[1024];
int i,nb ;
fpos_t beginning_of_line;
i=0;
scanf("%d",&nb) ;
f = fopen("dict.txt", "r+t");
while (i<nb)
{
fgetpos(f, &beginning_of_line);
fgets(ch, 1024, f);
i++;
}
fseek(f, beginning_of_line, SEEK_SET); // return to beginning of line
for (i = 0; ch[i] != '\n'; ++i) {
fputc('*', f);
}
fclose(f);
}
My file looks like:
123456789
My code gives me segmentation fault:
#include <stdio.h>
int main(){
FILE *f;
char ch[5];
f = open("a.txt", "r");
fgets( ch, 4, f);
ch[4] = NULL;
printf("%s", ch); //Fixed
return 0;
}
I am an absolute beginner. What am I doing wrong. My aim is to read first 4 characters of the file using fgets.
You'll want to do
printf("%s", ch);
For the % format, the argument is a pointer to characters; by passing a single character by value, you're telling printf to interpret that character's ASCII value as a pointer, and that's going to blow up on you; i.e., if the character is a 1, which is ASCII 49, then it's going to look at byte 49 in memory for a string -- and looking down there is generally verboten.
But secondly, I see you're calling open() instead of fopen(). You must use fopen() or you won't get a FILE* as you're expecting.
Both of these individually would likely cause a segfault -- you'll need to fix them both.
try to use "fopen" instead just "open"
Thanks.
Couple of quick changes.
I think you want to use fopen rather than open here, since you used a file pointer.
You need to increase the bytes read to 5, the last one is terminated by a null by fgets.
int main() {
FILE *f;
char ch[5];
f = fopen("a.txt", "r");
fgets( ch, 5, f);
printf("%s", ch);
return 0;
}
try to use
#include <stdio.h>
int main(){
FILE *f;
char ch[5];
f = fopen("a.txt", "r"); //use fopen
fgets( ch, 4, f);
ch[4] = NULL;
printf("%s", ch); // modification here pass the address of an array to printf
return 0;
}
try following example from the refereed site
/* fgets example */
#include <stdio.h>
int main()
{
FILE * pFile;
char mystring [5];
pFile = fopen ("myfile.txt" , "r");
if (pFile == NULL) perror ("Error opening file");
else {
if ( fgets (mystring , 5 , pFile) != NULL )
puts (mystring);
fclose (pFile);
}
return 0;
}
refer http://www.cplusplus.com/reference/clibrary/cstdio/fgets/
you can also use
fgetc() :Get character from stream (function)