Reading text from stdin (without fopen) - c

I'm trying to write some code to read my text file from stdin char by char, line by line, without using fopen. I need 42 lines with a maximum of 100 chars.
Help me to get this working and explain to me how it works. Thank you!
int main()
{
char str[100];
fgets(str, sizeof(str), stdin);
fputs(str, stdout);
return 0;}

without using fopen
If open is tolerated. Why not use it with read ? This solution will allow you to read char by char.
int main(void)
{
int file_descriptor = open("./path", O_RDWR); /* Open with read/write */
char text_block[10]; // Random size
read(file_descriptor, text_block, 1); /* This will read 1 characters
from the file */
/* Then do what you want with the char readed. */
}
Considering this solution, here is a process which will work :
Use stat() function to know the size of the file (read the manual)
Use the same process as above but instead of read 1 char read the size of the file
Each line is separated by '\n' exept the last one. Just use this to separate your fully readed file into lines
I guess it's for homework... This code have an error and won't compile until you found it. Which mean search the manual on the net and read it.

Related

What do I need to do to read a file then pick a line and write it to another file (Using C)?

I've been trying to figure out how I would, read a .txt file, and pick a line of said file from random then write the result to a different .txt file
for example:
.txt
bark
run
car
take line 2 and 3 add them together and write it to Result.txt on a new line.
How would I go about doing this???
I've tried looking around for resources for fopen(), fgets(), fgetc(), fprintf(), puts(). Haven't found anything so far on reading a line that isn't the first line, my best guess:
-read file
-print line of file in memory I.E. an array
-pick a number from random I.E. rand()
-use random number to pick a array location
-write array cell to new file
-repeat twice
-make newline repeat task 4-6
-when done
-close read file
-close write file
Might be over thinking it or just don't know what the operation to get a single line anywhere in a file is.
just having a hard time rapping my head around it.
I'm not going to solve the whole exercise, but I will give you a hint on how to copy a line from one file to another.
You can use fgets and increment a counter each time you find a line break, if the line number is the one you want to copy, you simply dump the buffer obtained with fgets to the target file with fputs.
#include <stdio.h>
#include <string.h>
int main(void)
{
// I omit the fopen check for brevity
FILE *in = fopen("demo.c", "r");
FILE *out = fopen("out.txt", "w");
int ln = 1, at = 4; // copy line 4
char str[128];
while (fgets(str, sizeof str, in))
{
if (ln == at)
{
fputs(str, out);
}
if (strchr(str, '\n') && (ln++ == at))
{
break;
}
}
fclose(in);
fclose(out);
return 0;
}
Output:
int main(void)

How to move the position pointer to next line in the file using fseek

I have seen programs for file handling and in one of the program using fseek as shown below:
/* This example opens a file myfile.dat for reading.
After performing input operations (not shown), it moves the file
pointer to the beginning of the file.
*/
#include <stdio.h>
int main(void)
{
FILE *stream;
int result;
if (stream = fopen("myfile.dat", "r"))
{ /* successful */
if (fseek(stream, 0L, SEEK_SET)); /* moves pointer to */
/* the beginning of the file */
{ /* if not equal to 0
then error ... */
}
else {
/* fseek() successful */
}
}
Like this can one move the file pointer to the next line immediately after that line
BO_ 377 FC_DM_MISC: 8 FC
SG_ DATA3 m11 : 31|8#0+ (1,0) [0|0] "" DM
These are the two lines and I want to program in a way that when one identifies the number 377 the pointer should now go to the next line i.e., to the line SG_ DATA3 inspite of the white spaces after 8 FC. How can one do that using fseek in C?
Try this code . It may help you .Here the Each line of the Input file is converted to string ,since string manipulation is very simple comparing to complex fseek() function.This may not be perfect answer but this will be very simple solution.
#include <stdio.h>
#include <string.h>
int main(void)
{
FILE *stream;
int result;
char tmp[100]; // assuming that max length of a line in myfile.dat is 100.
if (stream = fopen("myfile.dat", "r"))
{ /* successful */
fscanf(stream, "%100[^\n]", tmp); // assuming that max length of a line in myfile.dat is 100.
printf("%s", tmp);
if (strstr(tmp, "377"))
{ // check for 337
fscanf(stream, "%100[^\n]", tmp); // next line is in the string tmp .
// continue your program.
//printf("%s", tmp);
}
}
}
fseek is used for binary data, if you work on a text file you should use either fgets or getline(recommended to use getline).
There's an open discussion of "fgets() vs getline" and many say that "fgets is deprecated" is only a gcc propaganda in favor to their specific getline().
A possible flaw in fgets() is that it doesn't tell you anything if there are null bytes being read, something you can get away with getline().
But then again if you don't like gcc, or use something different, use fgets(). If you are stuck with gcc, then use getline().

How to read text file in C?

I'm trying to read a txt file containing strings of 1s and 0s and print it out in the manner below. I tried my code a couple of months ago and it worked fine in reading the text file. Now when I tried it, it outputs something really strange. Also I tried changing the directory of the file to a non-existant file but it still outputs the same thing when it should've quit the program immediately. Please help!
The content of txt file:-
10000001
01110111
01111111
01111010
01111010
01110111
Expected output:-
data_in<=24'b10000001;
#10000;
Real output:-
data_in<=24'b(some weird symbol that changes everytime I recompile);
#10000;
My code:-
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[])
{
int i, j;
j = 0;
char words[50];
FILE *fp;
fp = fopen (argv[1], "r");
if (fp == NULL) {
printf ("Can't open file\n");
}
while (feof (fp) == 0) {
fscanf (fp, "%s", words);
printf ("data_in<=24'b%s\n", words);
printf ("#10000\n");
}
fclose (fp);
system ("PAUSE");
return 0;
}
The input argument is the following:-
"C:\Users\Beanz\Documents\MATLAB\football frame\frame1.txt"
Read each line one by one with getline(3) -if available- or with fgets (you'll then need a large enough line buffer, at least 256 bytes), then parse each line buffer appropriately, using sscanf (the %n might be useful, and you should test the scanned item count result of sscanf) or other functions (e.g. strtok, strtol, etc...)
Remember that 'feof()' is only set AFTER trying to read PAST the end of the file, not when at the end of the file.
So the final iteration through the loop will try to read/process data that contains trash or prior contents.
Always check the returned value from 'fscanf()' before trying to use the associated data.
strongly suggest
eliminate the call to feof() and use the fscanf() to control the loop

stat system call reports "No such file or directory"

I'm working on a homework assignment and I ran into a little snag.
I'm trying to read a filename from standard input and then stat the file to get the size (as per the assignment's requirements):
#define BUFFSIZE 4096
int
main(void) {
int n;
char buffer[BUFFSIZE];
struct stat buf;
while ((n = read(STDIN_FILENO, buffer, BUFFSIZE)) > 0) {
stat(buffer, &buf);
perror("stat");
}
}
Here's the output when ran (I entered the filename file):
file
stat: No such file or directory
But if I try something like this:
#define BUFFSIZE 4096
int
main(void) {
int n;
char buffer[BUFFSIZE] = "file";
struct stat buf;
stat(buffer, &buf);
perror("stat");
}
I get:
stat: Success
The file named file is in the directory that I'm running the program from.
How come there is a difference between reading in the string "file" and just initializing the array to the string "file"?
Before calling stat() print the value of buffer to standard output:
printf("[%s]\n", buffer);
It will not be what you expect as read() will not NULL terminate buffer for you.
Initialise buffer before read().
Not sure why you looping on the read() as you should acquire the complete name of the file before calling stat(). If you have not been forced to use read() consider using fgets().
Did you try printing the buffer? Most likely your read call returned a newline on the end of the string "file," and there is no file "file\n" in your directory. I would recommend using fgets instead to read the filename from the console. Use standard C input/output when you can, and only delegate to platform-specific code when there is a measurable benefit (e.g. there is no cross-platform stat function in the C standard library, and sometimes Unix I/O can measurably improve performance).
There is a '\n' in the buffer in the 1st snippet. Take it out
buffer[strlen(buffer) - 1] = 0;
The problem is that the read leaves the newline in the buffer, so you try to stat "file\n".
read() may be reading too much (or not enough) on the first loop. Try printing out what it's read just before the stat() call:
printf("Read %d characters (%s)\n",n,buf);
read() is probably a bit low level for this task - I'd recommend using scanf() instead.
while ( scanf ("%s",buffer) == 1) {
For safe code, you'll need to specify the maximum number of characters to read, which you can do like this:
while ( scanf ("%4096s",buffer) == 1) {
However, if you want to use the BUFFSIZE macro, you'll need to do a bit of mucking about:
#define XLIM_PERCENT_S(x) "%" #x "s"
#define LIM_PERCENT_S(x) XLIM_PERCENT_S(x)
....
while ( scanf ( LIM_PERCENT_S( BUFFSIZE ) , buffer) == 1) {

C file read by line up to a custom delimiter

Is there a function in C to read a file with a custom delimiter like '\n'?
For example: I have:
I did write \n to exemplify in the file is the LF (Line feed, '\n', 0x0A)
this is the firstline\n this is the second line\n
I'd like the file to read by part and split it in two strings:
this is the firstline\n
this is the second line\n
I know fgets I can read up to a num of characters but not by any pattern. In C++ I know there is a method but in C how to do it?
I'll show another example:
I'm reading a file ABC.txt
abc\n
def\n
ghi\n
With the following code:
FILE* fp = fopen("ABC.txt", "rt");
const int lineSz = 300;
char line[lineSz];
char* res = fgets(line, lineSz, fp); // the res is filled with abc\ndef\nghi\n
fclose(fp);
I excpected fgets had to stop on abc\n
But the res is filled with: abc\ndef\nghi\n
SOLVED: The problem is that I was using Notepad++ in WindowsXP (the one I used
I don't know it happens on other windows) saved the file with different
encoding.
The newline on fgets needs the CRLF not just the CR when you type
enter in notepad++
I opened the windows notepad And it worked the fgets reads the string
up to abc\n on the second example.
fgets() will read one line at a time, and does include the newline character in the line output buffer. Here's an example of the common usage.
#include <stdio.h>
#include <string.h>
int main()
{
char buf[1024];
while ( fgets(buf,1024,stdin) )
printf("read a line %lu characters long:\n %s", strlen(buf), buf);
return 0;
}
But since you asked about using a "custom" delimiter... getdelim() allows you to specify a different end-of-line delimiter.

Resources