How to open a .txt file in Ubuntu with C?
How to open a .txt file in Ubuntu with C?
Before you open a text file, or any other file, in C, you need to study a good book on the C Programming Language. You need a lot more knowledge about C so you know what to do after opening the file.
You need to study a good book, cover to cover, and do all the exercises at the end of each chapter! Choose one of the three listed below:
C Programming, A Modern Approach
Author: K. N. King
C Primer Plus, 6th Edition
Stephen Prata
C How to Program, 8/e
Deitel & Deitel
Only then you will be ready to begin programming in the C Language.
Unfortunately, I don't have much time due to everyday routine. So it would help me a lot if you helped me with this.
We all have a "everyday routine". If you cannot commit to learning the language from a qualified instructor or from an up-to-date book, then I cannot help you further. Without properly learning the language, as with any other skill, you will, and are in over your head.
Just in case this is still an unresolved question, I have pasted in a Windows C solution with helpful comments
Code:/* Preparation 1) create a file: AccessThisFile.txt 2) Enter the following text: "I have accessed this file And this is the second line of the file" */ #include<stdio.h> #include<stdlib.h> #include<string.h> int main() { FILE *FileP; // A pointer used with files char FileContent[]=""; // Used to write the file content to a string char TheFileName[]="AccessThisFile.txt"; // the file is in the same folder as // this .c file // Now open the file to read from it FileP = fopen(TheFileName,"r"); // r means to read from // or //FileP = fopen("AccessThisFile.txt","r"); // This will also work // // Now read from the file // Method 1 // fscanf(FileP,"%s", FileContent); // will read in until the first space and stop // printf("\n%s", FileContent); // output: I // Method 2 // fgets(FileContent, 70, (FILE*) FileP); // will read in 70 characters, up to the // printf("\n%s", FileContent); // end of line. Output: I have accessed this file // // Method 3, no need for char FileContent[]=""; while( !feof(FileP) ) // go through the file one character at a time until you { // reach the end of the file, tested by feof char c = fgetc(FileP); // c is one character, not previously declared printf("%c", c); // as each character is read into c, print it to screen } fclose(FileP); // now close the file return 0; }
> while( !feof(FileP) )
See here as to why this is bad.
Why it's bad to use feof() to control a loop - Cprogramming.com
> char FileContent[]=""
...
> // fgets(FileContent, 70, (FILE*) FileP); // will read in 70 characters
1. The cast is pointless.
2. Your buffer isn't at least 70 chars.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.