Reading a specific sequence of characters from text file in C - c

If I`ve got a TXT file with a pre-determined structure, is there any way I can read some of the text directly from the file without having to parse or tokenize a string? For instance, if I have the following code:
#include <stdlib.h>
#include <stdio.h>
#include <cstring>
#include <fstream>
int main(int argc, char** argv) {
FILE* test = fopen("test.txt","w+");
char* read;
fprintf(test,"(foo,_TEMP71_,_,_)\n");
fprintf(test,"(foo,_TEMP52_,_,_)\n");
fprintf(test,"(foo,_TEMP43_,_,_)\n");
fprintf(test,"(foo,_TEMP24_,_,_)\n");
fprintf(test,"(foo,_TEMP15_,_,_)\n");
fprintf(test,"(foo,_TEMP06_,_,_)\n");
fseek(test, 0, SEEK_SET); //returns the file pointer to start of file
while(feof(test) == 0)
{
fscanf(test, "_%s_", read); //or fscanf(test, "_TEMP%s_", read);
printf("%s\n", read);
}
fclose(test);
}
Note that on the fscanf line, I read from this website that you could specify a certain string of characters to be read, but I don`t think I understood quite how it works.

Related

How to paste the contens of a text file including foreign characters

I'm trying to read a .txt file with UTF-8 encoding and paste it's contents to a
string so I can parse it later.
The issue is the copied contents aren't correct. Non-English characters are not only read wrong, but they are also copied as 2 or more random characters onto the string.
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <locale.h>
void main()
{
setlocale(LC_ALL, "Turkish");
FILE *dosya = fopen("InsertFilePath", "r");
char yazi[1000];
char c;
yazi[0] = '\0';
fseek(dosya, 0, SEEK_SET);
while((c = fgetc(dosya)) != EOF)
{
strncat(yazi, &c, 1);
}
printf("%s", yazi);
}
this code prints out:
Nesneye Yönelik Programlama Türkçe Karakter
instead of:
Nesneye Yönelik Programlama Türkçe Karakter
As the troublesome characters in question are Turkish I put this line in the code: setlocale(LC_ALL, "Turkish");
Though, it doesn't seem to help.

How to write text containing newline given as command line arguments in C?

I want to create a text file with mulitple lines using system calls in C and populate it with the text provided as command line arguments.
This is what I wrote:
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define MAX_SZ 1024
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Invalid Number of arguments\n");
printf("USAGE: ./a.out file_name \"msg\"\n");
} else {
int fd_creat, fd_open, fd_write;
char file_name[MAX_SZ];
char *msg = (char *)malloc(strlen(argv[2]) * sizeof(char));
strcpy(file_name, argv[1]);
fd_creat = creat(file_name, 0777);
if (fd_creat < 2) {
printf("ERROR: File could not be created\n");
} else {
fd_open = open(file_name, O_WRONLY);
strcpy(msg, argv[2]);
fd_write = write(fd_open, msg, strlen(msg));
close(fd_open);
}
}
return 0;
}
If I execute this program as:
./a.out test.txt "Foo\nBar"
It writes the whole thing into test.txt as it is. Basically, I want 'Foo' and 'Bar' in their separate lines.
There's two problems here:
The way you're handling arguments and failing to allocate enough memory for the data involved,
Interpreting escape sequences like \n correctly since the shell will give them to you as-is, raw.
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
// This moves overlapping strings from src -> dest but only
// if dest is before src
void cc_str_drag(char* dest, char* src) {
while (*dest) {
*dest = *src;
++dest;
++src;
}
}
// This interprets the \n sequence and can be extended to handle others, like
// \t, \\, or even \g.
void cc_interpret(char* str) {
for (;*str; ++str) {
// If this is a sequence start...
if (*str == '\\') {
// ...find out which one...
switch (str[1]) {
case 'n':
// Shift back...
cc_str_drag(str, &str[1]);
// ...and replace it.
*str = '\n';
break;
}
}
}
}
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Invalid Number of arguments\n");
// Remember argv[0] is the name of the program
printf("USAGE: %s file_name \"msg\"\n", argv[0]);
return -1;
}
// Since it's not the 1970s, use fopen() and FILE*
FILE* output = fopen(argv[1], "w");
if (!output) {
printf("ERROR: File could not be created\n");
return -2;
}
// Copying here to avoid tampering with argv
char* str = strdup(argv[2]);
// Replace any escape sequences
cc_interpret(str);
// Then just dump it directly into the file
fwrite(str, 1, strlen(str), output);
fclose(output);
return 0;
}
Note the tools used here:
strdup is a way quicker method of copying a C string than malloc(strlen(s)) and then copying it. That's asking for dreaded off-by-one errors.
FILE* performs much better because it's buffered. open() is used for low-level operations that can't be buffered. Know when to use which tool.
Don't be afraid to write functions that manipulate string contents. C strings are really important to understand, not fear.

Why does the program print only the last line of the file, even after reading the entire file?

I want to write a program in C which just reads a file, stores it into an array and then prints the array. Everything works fine but when the text file has more than one line, I always just get the last line printed out.
This is my Code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char * argv[]) {
FILE * stream;
char dateiname[255];
stream = fopen("heute.txt", "r");
if(stream == NULL){
printf("Error");
}else {
while(!feof(stream)){
fgets(dateiname, 255, stream);
}
fclose(stream);
}
printf("%s\n", dateiname);
}
Thanks for help!
Everything works fine but when the text file has more than one line, I always just get the last line printed out
Reason: For every iteration, the data gets replaced with the next line data, and at the end dateiname will read only the last line.
while(!feof(stream))
Usage of feof() is not recommended. Please see this link for more information :https://faq.cprogramming.com/cgi-bin/smartfaq.cgi?id=1043284351&answer=1046476070
Please see the following code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *stream;
char dateiname[1024];
int i = 0;
stream = fopen("heute.txt", "r");
if (stream == NULL)
{
printf("Error");
}
else
{
while (fgets(dateiname, sizeof(dateiname), stream) != NULL)
{
printf("Line %4d: %s", i, dateiname);
i++;
}
}
return 0;
}
If you want to just read and print the contents of the file you no need to worry about the size of the file and how many number of lines you have in file.
you can just run fgets() in the while and print each line until we reach NULL
But if you want to store them, we need to calculate the size of the file.
So we need to use functions like stat or fstat to get the size of the file and allocate memory dynamically then just read that many bytes.

Implementing rev command in C using POSIX system functions

I am trying to implement the rev linux call in C using only system calls. I was able to implement it but my code also reverses the lines of the files as well so line 1 is the last line in the file now. The last line also does not jump into a new line on stdout. I'm not sure why it is doing this.
Here is my code:
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#define LINE_BUFFER 1024
int charCount(const char *name1);
int main(int argc, char* argv[]) {
if(argc ==2){
charCount(argv[1]);
}else{
printf("Provide a file\n");
}
return 0;
}
int charCount(const char *name1)
{
char buffer[LINE_BUFFER];
int fd;
int nread;
int i = 0;
if ((fd = open(name1, O_RDONLY)) == -1)
{
perror("Error in opening file");
return (-1);
}
int size = lseek(fd,-1,SEEK_END);
while(size>=0)
{
nread=read(fd,buffer,1);
write(1,buffer,1);
lseek(fd, -2,SEEK_CUR);
size--;
}
close(fd);
return(0);
}
input
Contents of file 1:
Hello World
Hi World
Output
dlroW iH
dlroW olleH
Desired output:
dlroW olleH
dlroW iH
Your code clearly reads the file backwards, one character at a time, printing each character as it reads it. Why would you think it would reverse line by line? It makes no attempt to even notice where each line ends.
If you read a file backwards, the last character you'll read (and therefore the last character you'll print) is the first character in the file, which is not normally a newline character.

Using fscanf to store words from file in an array

I am trying to write a program for some classwork that reads in a file using fscanf, and then stores each word into an array with one word in each element. Then I need to print each element of the array out on to a new line on the console.
The getty.txt file has the Gettysburg address in it with appropriate spacing, punctuation, and is multiline.
What I think is happening is that the entire text is being stored in the first element of the array, but I am not 100% sure as I am still learning to debug and write in C.
Any advice as to what I am doing wrong would be great! I currently only seem to be getting the last word and some extra characters.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void readFile();
void writeFile(char* buffer, int bufferlen);
FILE *fpread;
FILE *fpwrite;
char filebuffer[1000];
int filebufferlen = 0;
int main(int argc, char *argv[]) {
fpwrite = fopen("csis.txt", "w");
readFile();
writeFile(filebuffer, filebufferlen);
fclose(fpwrite);
return 0;
}
void readFile() {
char c;
filebufferlen = 0;
if(!(fpread = fopen("getty.txt", "r"))){
printf("File %s could not be opened. \n", "getty.txt");
fprintf(fpwrite,"File %s could not be opened. \n", "getty.txt");
exit(1);
}
while (!feof(fpread)) {
fscanf(fpread, "%s", filebuffer);
filebufferlen++;
}
}
void writeFile(char* filebuffer, int filebufferlen) {
for (int i = 0; i < filebufferlen; ++i){
printf("%c\n", filebuffer[i]);
}
}
After fixing the compile problems:
the code does not contain any code nor data declarations to contain an array of 'words.' So naturally, nothing but the last word is actually saved so it can be printed out.

Resources